﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;

using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.IO;
using Microsoft.Office.Interop.Word;
using System.Diagnostics;
using System.Threading;
using Oracle.DataAccess.Client;
using System.Data.SqlClient;
using System.Runtime.InteropServices;
using WordAutoGre.Properties;


namespace WordAutoGre
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public Dictionary<string, Dictionary<string, TableInfo>> dic = new Dictionary<string, Dictionary<string, TableInfo>>();

        bool cache_is_readying = true;

        private void button1_Click(object sender, EventArgs e)
        {
            TestConnect();
        }
        [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
        public static extern IntPtr GetDesktopWindow();
        [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
        public static extern bool RedrawWindow(IntPtr hwnd, COMRECT rcUpdate, IntPtr hrgnUpdate, int flags);

        public class COMRECT
        {
            public int left;
            public int top;
            public int right;
            public int bottom;
            public COMRECT()
            {
            }
            public COMRECT(int left, int top, int right, int bottom)
            {
                this.left = left;
                this.top = top;
                this.right = right;
                this.bottom = bottom;
            }
        }
        void InitCache()
        {
            if (!cache_is_readying) return;

            string[] tabs = GetAllTableName(true);
            string ckey = userControl11.MyText.Trim();

            cache_is_readying = false;
            if (tabs.Length != 0)
            {

                if (!dic.ContainsKey(ckey))
                {
                    dic[ckey] = new Dictionary<string, TableInfo>();
                }

                for (int i = 0; i < tabs.Length; i++)
                {
                    dic[ckey][tabs[i]].dt = GetColumnsDesc(tabs[i], true, true);
                }

            }
            cache_is_readying = true;

        }
        string[] SelectArray(string[] rsts, string str, bool ingoreCase = true)
        {
            List<string> tl = new List<string>();
            List<string> tlr = new List<string>();
            if (ingoreCase) str = str.ToLower();
            foreach (string item in rsts)
            {
                string titem = ingoreCase ? item.ToLower() : item;
                if (titem.Contains(str))
                {
                    tl.Add(item);
                }
                else
                {
                    tlr.Add(item);
                }
            }
            tl.AddRange(tlr);
            return tl.ToArray();
        }
        string[] _tabs = new string[0];
        DateTime _tabtime = DateTime.Now.AddSeconds(-10);
        string[] GetAllTableName(bool isForce = false)
        {
            if (!isForce && (DateTime.Now - _tabtime).TotalSeconds < 8 && _tabs.Length != 0)
            {
                return _tabs;
            }
            switch (sif.DataBaseType)
            {
                case 0:
                    _tabs = ReadMyData("show tables");
                    break;
                case 1:
                    _tabs = ReadMyData("select TABLE_NAME from user_tables");
                    break;
                case 2:
                    _tabs = ReadMyData("select name from sys.tables");
                    break;
                default:
                    break;
            }
            if (_tabs == null) _tabs = new string[0];
            _tabtime = DateTime.Now;
            return _tabs;
        }
        void AddDataToComBoBox(string[] tabs)
        {
            if (tabs != null && tabs.Length != 0)
            {
                string str = comboBox1.Text;
                comboBox1.Items.Clear();
                comboBox1.Update();
                comboBox1.Items.AddRange(tabs);
                if (!(new List<string>(tabs)).Contains(str) || str == "") str = tabs[0];
                comboBox1.Text = str;
                comboBox1.Select(comboBox1.Text.Length, 0);
            }
        }
        string[] GetComBoBoxData()
        {
            List<string> ls = new List<string>();
            if (comboBox1.Items.Count != 0)
            {

                foreach (var item in comboBox1.Items)
                {
                    ls.Add(item.ToString());
                }
            }
            return ls.ToArray();
        }
        private void TestConnect()
        {
            if (userControl11.MyText.Trim() == "")
            {
                SetText("连接字符串不能为空!");
                SetStatus("连接字符串不能为空!");
                MessageBox.Show("连接字符串不能为空!", "连接字符串", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            string[] tabs = GetAllTableName(true);
            if (tabs.Length != 0)
            {
                new Thread(InitCache).Start();
                userControl11.AddItem();

                dic[userControl11.MyText] = new Dictionary<string, TableInfo>();

                for (int i = 0; i < tabs.Length; i++)
                {
                    dic[userControl11.MyText][tabs[i]] = new TableInfo(tabs[i], i);
                }
                AddDataToComBoBox(tabs);
                string str = comboBox1.Text;
                if (sif.DataSource)
                {
                    DisplayDataString = userControl11.MyText;

                    if (str != "" && (new List<string>(tabs)).Contains(str))
                    {
                        comboBox1.Text = str;
                    }

                }
                else
                {
                    if ((new List<string>(tabs)).Contains(comboBox1.Text))
                    {
                        string Tabdesc = GetTableDesc(comboBox1.Text, true, true);
                        dic[userControl11.MyText][comboBox1.Text].Description = Tabdesc;
                        dic[userControl11.MyText][comboBox1.Text].TabName = comboBox1.Text;
                        DataTable dt = GetColumnsDesc(comboBox1.Text, true);
                        dic[userControl11.MyText][comboBox1.Text].dt = dt;
                    }

                }
                if (str != "")
                    RefreashData();
                SetStatus("连接成功!");
            }
            else
            {
                SetStatus("连接失败!");
            }

        }
        private void SetText(string title)
        {
            this.Text = "WordAutoGre  --  " + title + "  --  ZhuShengWen";
        }
        public DataTable GetColumnsDesc(string TabName, bool isTest = false, bool isForceGet = false)
        {
            if (sif.DataSource || isTest)
            {
                try
                {
                    if (!isForceGet)
                        if (dic.ContainsKey(DisplayDataString))
                        {
                            if (dic[DisplayDataString].ContainsKey(TabName))
                            {
                                if (dic[DisplayDataString][TabName].dt != null)
                                    return dic[DisplayDataString][TabName].dt;
                            }
                        }
                    DataTable dt = new DataTable();//"SELECT column_name 字段名称,column_type 字段类型,column_comment 详细说明,is_nullable 空否,CASE COLUMN_KEY WHEN 'PRI' THEN	'主键' ELSE	'' END 约束条件 FROM information_schema.COLUMNS WHERE	table_name = 'data_ggsy_sfcx';";
                    switch (sif.DataBaseType)
                    {
                        case 0:
                            string SqlString = "SELECT column_name,column_type,is_nullable,CASE COLUMN_KEY WHEN 'PRI' THEN	'主键' ELSE '暂无' END COLUMN_CONSTRICT, column_comment FROM information_schema.COLUMNS WHERE TABLE_SCHEMA='" + MySql_SCHEMA + "' and 	table_name = '" + TabName + "'";// ORDER BY COLUMN_CONSTRICT desc;";
                            MySqlDataAdapter msda = new MySqlDataAdapter(SqlString, userControl11.MyText);
                            msda.Fill(dt);
                            break;
                        case 1:
                            SqlString = "SELECT  t.COLUMN_NAME, t.DATA_TYPE || '(' || t.DATA_LENGTH || (case when t.DATA_PRECISION is null then '' else ',' || t.DATA_PRECISION end) || ')' COLUMN_TYPE, case when t.NULLABLE = 'Y' then 'YES' else 'NO' end is_nullable, case when c.constraint_type = 'P' then '主键' when c.constraint_type = 'R' then '外键' else '暂无' end COLUMN_CONSTRICT, cm.comments column_comment from (SELECT * from sys.all_tab_cols t where t.table_name='" + TabName + "') t left join user_cons_columns cc on t.TABLE_NAME = cc.TABLE_NAME and t.COLUMN_NAME = cc.COLUMN_NAME and substr(cc.constraint_name,0,3) <> 'SYS'  left join (select ucc.table_name,ucc.column_name,wmsys.wm_concat(uc.constraint_type) constraint_type from SYS.USER_CONS_COLUMNS ucc left join user_constraints uc on ucc.constraint_name=uc.constraint_name and ucc.table_name=uc.table_name and uc.constraint_type is not null and (uc.constraint_type='P' or uc.constraint_type='R') group by (ucc.table_name,ucc.column_name)) c on t.TABLE_NAME=c.table_name and t.COLUMN_NAME=c.COLUMN_NAME left join user_col_comments cm on t.TABLE_NAME = cm.TABLE_NAME and t.COLUMN_NAME = cm.COLUMN_NAME where t.TABLE_NAME = '" + TabName + "' order by column_id";
                            OracleDataAdapter olda = new OracleDataAdapter(SqlString, userControl11.MyText);
                            olda.Fill(dt);
                            break;
                        case 2:
                            SqlString = "SELECT SC.name,ST.name+'('+ ltrim(str(SC.length)) +')' type, (case when SC.isnullable=0 then 'NO' else 'YES' end) NULL_ABLE , case when SC.name in (select COLUMN_NAME = convert(sysname,c.name) from sysindexes i, syscolumns c, sysobjects o where o.id = object_id('[{0}]') and o.id = c.id and o.id = i.id and (i.status & 0x800) = 0x800 and (c.name = index_col ('[{0}]', i.indid, 1) or c.name = index_col ('[{0}]', i.indid, 2) or c.name = index_col ('[{0}]', i.indid, 3) or c.name = index_col ('[{0}]', i.indid, 4) or c.name = index_col ('[{0}]', i.indid, 5) or c.name = index_col ('[{0}]', i.indid, 6) or c.name = index_col ('[{0}]', i.indid, 7) or c.name = index_col ('[{0}]', i.indid, 8) or c.name = index_col ('[{0}]', i.indid, 9) or c.name = index_col ('[{0}]', i.indid, 10) or c.name = index_col ('[{0}]', i.indid, 11) or c.name = index_col ('[{0}]', i.indid, 12) or c.name = index_col ('[{0}]', i.indid, 13) or c.name = index_col ('[{0}]', i.indid, 14) or c.name = index_col ('[{0}]', i.indid, 15) or c.name = index_col ('[{0}]', i.indid, 16) ) ) then '主键' when SC.name in(select t1.name from (select col.name, f.constid as temp from syscolumns col,sysforeignkeys f where f.fkeyid=col.id and f.fkey=col.colid and f.constid in ( select distinct(id) from sysobjects where OBJECT_NAME(parent_obj)='{0}' and xtype='F' ) ) as t1 , (select OBJECT_NAME(f.rkeyid) as rtableName,col.name, f.constid as temp from syscolumns col,sysforeignkeys f where f.rkeyid=col.id and f.rkey=col.colid and f.constid in ( select distinct(id) from sysobjects where OBJECT_NAME(parent_obj)='{0}' and xtype='F' ) ) as t2 where t1.temp=t2.temp ) then '外键' else '暂无' end check_1, SEP.value FROM syscolumns SC left join systypes ST on SC.xusertype = ST.xusertype LEFT JOIN sys.columns SYC on SYC.object_id = SC.id and SYC.name=SC.name LEFT JOIN sys.extended_properties SEP on SEP.major_id = SYC.object_id AND SEP.minor_id = SYC.column_id where SC.id = object_id('{0}')";
                            SqlString = string.Format(SqlString, TabName);
                            SqlDataAdapter sqda = new SqlDataAdapter(SqlString, userControl11.MyText);
                            sqda.Fill(dt);
                            break;
                        default:
                            break;
                    }
                    return dt;
                }
                catch (Exception e)
                {

                    SetText("数据库无法连接!");
                    SetStatus(e.Message);
                    MessageBox.Show("数据库无法连接!", "连接数据库异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return null;
                }

            }
            else
            {
                if (dic.ContainsKey(DisplayDataString))
                {
                    if (dic[DisplayDataString].ContainsKey(TabName))
                    {
                        return dic[DisplayDataString][TabName].dt;
                    }
                }
                return null;
            }
        }
        private void EnterPressed(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                TestConnect();
            }
        }
        private string MySql_SCHEMA
        {
            get
            {
                string temp = "";
                int sta = userControl11.MyText.ToLower().IndexOf("database");
                if (sta == -1) return "";
                int end = userControl11.MyText.ToLower().IndexOf(";", sta + 8);
                if (sta != -1)
                {

                    if (end != -1)
                    {
                        temp = userControl11.MyText.Substring(sta + 8, end - sta - 8);
                    }
                    else
                    {
                        temp = userControl11.MyText.Substring(sta + 8);
                    }
                    temp = temp.Replace("=", "").Replace(" ", "");
                }
                return temp;
            }
        }
        string DisplayDataString = "";
        public string GetTableDesc(string TabName, bool ForceFetch = true, bool isTest = false)
        {

            if (!dic.ContainsKey(DisplayDataString))
            {
                SetText("请单击 测试连接 按钮或者设置数据源!");
                MessageBox.Show("请先获取表!", "表未获取!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return "";
            }
            if ((sif.DataSource && ForceFetch) || isTest)
            {
                DataTable dt = new DataTable();//"SELECT column_name 字段名称,column_type 字段类型,column_comment 详细说明,is_nullable 空否,CASE COLUMN_KEY WHEN 'PRI' THEN	'主键' ELSE	'' END 约束条件 FROM information_schema.COLUMNS WHERE	table_name = 'data_ggsy_sfcx';";
                string queryString = "";
                switch (sif.DataBaseType)
                {
                    case 0:
                        queryString = "select TABLE_COMMENT from information_schema.TABLES WHERE TABLE_SCHEMA='" + MySql_SCHEMA + "' and TABLE_NAME='" + TabName + "';";
                        break;
                    case 1:
                        queryString = "select comments from user_tab_comments where table_name='" + TabName + "'";
                        break;
                    case 2:
                        queryString = "select value from sysobjects SO left join sys.extended_properties p on SO.id=p.major_id where p.name='MS_Description' and minor_id=0 and SO.name='" + TabName + "'";
                        break;
                    default:
                        break;
                }

                string[] strs = ReadMyData(queryString);
                if (strs != null && strs.Length > 0)
                {
                    dic[DisplayDataString][TabName].Description = strs[0];
                    return strs[0];
                }
                else return "";
            }
            if (dic[DisplayDataString].ContainsKey(TabName))
                return dic[DisplayDataString][TabName].Description;
            else return "";
        }
        public string TempTxtPath
        {
            get
            {
                return Path.GetFullPath(Path.Combine(System.Environment.GetEnvironmentVariable("TEMP"), MyClass.GetNowTime().Replace(':', '-')));
            }
        }
        public string[] ReaderToArray(IDataReader reader)
        {
            List<string> tabs = new List<string>();
            // string str = "";
            try
            {
                List<string> ls = new List<string>();
                while (reader.Read())
                {
                    for (int i = 0; i < reader.FieldCount; i++)
                    {
                        //str += reader[i].ToString();
                        // str += "\r\n";
                        tabs.Add(reader[i].ToString());
                    }
                }
            }
            finally
            {
                // always call Close when done reading.
                reader.Close();
            }
            return tabs.ToArray();
        }
        public string[] ReadMyData(string queryString)
        {
            //"SELECT * FROM " + TableName + " LIMIT " + (PageNum * Count) + "," + Count;
            List<string> tabs = new List<string>();
            try
            {
                switch (sif.DataBaseType)
                {
                    case 0:
                        using (MySqlConnection connection = new MySqlConnection(userControl11.MyText))
                        {
                            MySqlCommand command = new MySqlCommand(queryString, connection);
                            connection.Open();
                            MySqlDataReader reader = command.ExecuteReader();
                            return ReaderToArray(reader);
                        }
                    case 1:
                        using (OracleConnection connection = new OracleConnection(userControl11.MyText))
                        {
                            OracleCommand command = new OracleCommand(queryString, connection);
                            connection.Open();
                            OracleDataReader reader = command.ExecuteReader();
                            return ReaderToArray(reader);
                        }
                    case 2:
                        using (SqlConnection connection = new SqlConnection(userControl11.MyText))
                        {
                            SqlCommand command = new SqlCommand(queryString, connection);
                            connection.Open();
                            SqlDataReader reader = command.ExecuteReader();
                            return ReaderToArray(reader);
                        }

                    default:
                        break;
                }

            }
            catch (Exception e)
            {
                SetText("数据库连接时发生异常,请检查数据库类型是否正确!");
                SetStatus(e.Message);
                MessageBox.Show("数据库抛出异常,请检查数据库类型是否正确!", "连接数据库异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }


            //  Console.WriteLine(str);
            return tabs.ToArray();
        }
        private void SetInfo()
        {
            string str = "表:" + comboBox1.Text + "在" + (sif.DataSource ? "数据库" : "文件") + "中";
            bool flag = false;
            if (dic.ContainsKey(DisplayDataString))
            {
                if (dic[DisplayDataString].ContainsKey(comboBox1.Text)) flag = true;
            }
            if (flag)
            {
                comboBox1.BackColor = System.Drawing.SystemColors.Window;
                SetText(str + "已找到!");
            }
            else
            {
                SetText(str + "未找到!");
                comboBox1.BackColor = System.Drawing.Color.PeachPuff;
                int RowCount = dataGridView1.Rows.Count - 1;
                dataGridView1.CurrentCell = null;
                for (; RowCount >= 0; RowCount--)
                    dataGridView1.Rows.RemoveAt(RowCount);
                SetTabDescByStr("");
            }
        }

        public bool ValidTable(string table = "", bool isTest = false)
        {
            string TabName = "";
            if (table != "") TabName = table;
            else TabName = comboBox1.Text;
            bool flag = false;
            string source = isTest == true ? userControl11.MyText : DisplayDataString;
            if (dic.ContainsKey(source))
            {
                if (dic[source].ContainsKey(TabName))
                    flag = true;
            }
            if (table == "" && !isTest) SetInfo();
            return flag;

        }
        private string GetTabDescByTextBox()
        {
            string temp = "";
            string[] strs = new string[] { textBox1.Text.Trim(), textBox2.Text.Trim(), textBox3.Text.Trim() };
            if (strs[0] != "")
                temp += strs[0];
            if (strs[1] != "" || strs[2] != "")
            {
                if (strs[1] != "" || strs[2] != "")
                {
                    temp += ";";
                    temp += strs[1];
                }
                if (strs[2] != "")
                {
                    temp += ";";
                    temp += strs[2];
                }
            }
            return temp;
        }
        private void SetTabDescByStr(string desc)
        {
            string[] strs = desc.Split(';');
            textBox1.Text = strs[0];
            if (strs.Length > 1) textBox2.Text = strs[1]; else textBox2.Text = "";
            if (strs.Length > 2) textBox3.Text = strs[2]; else textBox3.Text = "";
        }
        private string[] GetTabDescToArray(string desc)
        {
            string[] strs = desc.Split(';');
            string[] rts = new string[3];
            rts[0] = strs[0];
            if (strs.Length > 1) rts[1] = strs[1]; else rts[1] = "";
            if (strs.Length > 2) rts[2] = strs[2]; else rts[2] = "";
            return rts;
        }
        private void SaveTabDescription(string table = "", string desc = "")
        {
            if (table == "") table = comboBox1.Text;
            if (desc == "") desc = GetTabDescByTextBox();
            if (ValidTable(table))
            {
                if (desc != "")
                {
                    dic[userControl11.MyText][table].Description = desc;
                    desc = desc.Replace("'", "''");
                    string queryString = "";
                    switch (sif.DataBaseType)
                    {
                        case 0:
                            queryString = string.Format("alter table {0} comment '{1}'", table, desc);
                            break;
                        case 1:
                            queryString = string.Format("COMMENT ON TABLE {0} is '{1}'", table, desc);
                            break;
                        case 2:
                            try
                            {
                                SqlConnection sqlCon = new SqlConnection(userControl11.MyText);
                                SqlCommand sqlCmd = new SqlCommand("sp_executesql", sqlCon);
                                sqlCmd.CommandType = CommandType.StoredProcedure;//设置调用的类型为存储过程  

                                SqlParameter sqlParme;
                                sqlParme = sqlCmd.Parameters.Add("@sql", SqlDbType.NVarChar, 4000);
                                sqlParme.Direction = ParameterDirection.Input;
                                string name = "'MS_Description',";
                                string str = "'user','dbo','table','" + table + "',NULL,NULL";
                                string sql = "if (SELECT count(*) FROM ::fn_listextendedproperty (" + name + str + "))> 0 begin EXECUTE sp_updateextendedproperty " + name + "'" + desc.Replace("'", "''") + "'," + str + ";end else begin EXECUTE sp_addextendedproperty " + name + "'" + desc.Replace("'", "''") + "'," + str + ";end;";
                                sqlParme.Value = sql;
                                sqlCon.Open();
                                sqlCmd.ExecuteNonQuery();
                                sqlCon.Close();
                            }
                            catch (Exception e)
                            {
                                MessageBox.Show(e.Message, "修改表描述发生异常", MessageBoxButtons.OK, MessageBoxIcon.Error); ;
                            }

                            break;
                        default:
                            break;
                    }
                    ExecNonQuery(queryString);
                    SetStatus("表(" + table + ")描述已经提交!");
                }
            }
        }
        private void SaveColDescription(string queryString, string col_name, string tab_name)
        {
            if (ValidTable(tab_name, true))
            {
                ExecNonQuery(queryString);
                SetStatus("字段(" + col_name + "-" + tab_name + ")描述已经提交!");
            }
        }
        private bool ExecNonQuery(string queryString)
        {
            try
            {
                switch (sif.DataBaseType)
                {
                    case 0:
                        using (MySqlConnection connection = new MySqlConnection(userControl11.MyText))
                        {

                            MySqlCommand command = new MySqlCommand(queryString, connection);
                            connection.Open();
                            command.ExecuteNonQuery();
                            return true;
                        }
                    case 1:
                        using (OracleConnection connection = new OracleConnection(userControl11.MyText))
                        {

                            OracleCommand command = new OracleCommand(queryString, connection);
                            connection.Open();
                            command.ExecuteNonQuery();
                            return true;
                        }
                    case 2:
                        break;
                    default:
                        break;
                }

            }
            catch (Exception)
            {

                return false;
            }
            return true;
        }

        private void comboBox1_TextChanged(object sender, EventArgs e)
        {
            RefreashData();
            RedrawWindow(GetDesktopWindow(), null, IntPtr.Zero, 0x85);
        }
        private void SetCount()
        {
            string str = "";
            int a = 0;
            if (dic.ContainsKey(userControl11.MyText))
            {
                a = dic[userControl11.MyText].Count;
            }
            int b = 0;
            if (dic.ContainsKey(choseFile1.MyText))
            {
                b = dic[choseFile1.MyText].Count;
            }

            str += "表:" + a + "," + b + ";";
            str += "列:" + dataGridView1.RowCount;
            toolStripStatusLabel3.Text = str;
        }
        private bool RefreashData(bool isForceGet = false)
        {
            if (ValidTable())
            {
                string Tabdesc = GetTableDesc(comboBox1.Text, true);
                SetTabDescByStr(Tabdesc);
                dic[DisplayDataString][comboBox1.Text].Description = Tabdesc;
                int RowCount = dataGridView1.Rows.Count - 1;
                for (; RowCount >= 0; RowCount--)
                    dataGridView1.Rows.RemoveAt(RowCount);
                DataTable dt = GetColumnsDesc(comboBox1.Text, sif.DataSource, isForceGet);
                if (dt == null)
                {
                    return false;
                }

                for (int i = 0; i < dt.Rows.Count; i++)// item in dt.Rows)
                {
                    //dataGridView1.Rows.Add();
                    DataGridViewRow dgvr = new DataGridViewRow();
                    List<object> ro = new List<object>();
                    int ColCount = dt.Rows[i].ItemArray.Length;
                    string[] descs = dt.Rows[i].ItemArray[ColCount - 1].ToString().Split(';');
                    ro.Add(descs[0]);
                    for (int j = 0; j < ColCount; j++)
                    {
                        if (j == ColCount - 1)
                        {
                            if (descs.Length > 1)
                            {
                                string desc = dt.Rows[i].ItemArray[j].ToString();
                                int sta = desc.IndexOf(';');
                                ro.Add(desc.Substring(sta + 1));
                                break;
                            }

                        }
                        ro.Add(dt.Rows[i].ItemArray[j]);
                        //dataGridView1.Rows[i].Cells[j].Value = dt.Rows[i].ItemArray[j];
                        //dataGridView1[i, j].Value = (string);
                    }
                    dgvr.CreateCells(dataGridView1, ro.ToArray());
                    dataGridView1.Rows.Add(dgvr);

                }
                int Height = dataGridView1.ColumnHeadersHeight;
                foreach (DataGridViewRow item in dataGridView1.Rows)
                {
                    Height += item.Height;
                }
                if (Height < 300) Height = 300;
                if (Height > 450) Height = 400;
                dataGridView1.Height = Height + 2;
                this.Height = 240 + Height;
                StartPosition = FormStartPosition.CenterScreen;
                if (Location.Y + Height > Screen.PrimaryScreen.Bounds.Size.Height)
                    Location = new System.Drawing.Point(Location.X, (Screen.PrimaryScreen.Bounds.Size.Height - this.Height) / 2);
                //dataGridView1.DataSource = dt;

                return true;
            }
            return false;
        }
        List<string> stustring = new List<string>();
        private void SetStatus(string staString)
        {
            stustring.Add(staString);
        }
        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            System.Windows.Forms.CheckBox cb = (System.Windows.Forms.CheckBox)sender;
            if (cb.Checked)
            {
                textBox4.BackColor = System.Drawing.SystemColors.Window;
                textBox4.Enabled = true;
            }
            else
            {
                textBox4.BackColor = cb.Parent.BackColor;
                textBox4.Enabled = false;
            }
        }

        private void textBox1_Leave(object sender, EventArgs e)
        {
            AutoSaveTabDesc();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            SetText("正在强制刷新数据...");
            Thread.Sleep(200);
            bool r = RefreashData(true);
            if (r)
            {
                SetText("数据已刷新!");
                SetStatus("数据已刷新!");
            }
            else
            {
                SetStatus("数据刷新失败,请检查连接!");
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            SaveAll();
        }

        private void SaveAll()
        {
            if (!ValidTable()) return;
            SaveTabDesc();
            foreach (DataGridViewRow item in dataGridView1.Rows)
            {
                SaveCurrColDesc(item);
            }
            SetStatus("保存成功!");
        }
        int sec = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {
            this.toolStripStatusLabel4.Text = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            SetCount();
            int i = 2;
            i = 20 - stustring.Count;
            if (i < 2) i = 2;
            if (stustring.Count != 0)
            {
                toolStripStatusLabel1.Text = stustring[0];
                stustring.RemoveAt(0);
            }
            if (stustring.Count > 10)
            {
                int interval = 500 / (stustring.Count) * 10;
                if (interval <= 0) interval = 100;
                timer1.Interval = interval;
            }
            else timer1.Interval = 500;
            if (sec < i)
            {
                sec++;
                return;
            }

            sec = 0;
            if (stustring.Count == 0)
                toolStripStatusLabel1.Text = "欢迎使用本系统";


        }


        public Document CreateWord(string fileName)
        {
            Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
            Document WordDoc;
            string strContent = "";
            object strFileName = fileName;//System.Web.HttpContext.Current.Server.MapPath("test.doc");
            if (System.IO.File.Exists((string)strFileName))
                System.IO.File.Delete((string)strFileName);
            Object oMissing = System.Reflection.Missing.Value;
            WordDoc = WordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            #region   将数据库中读取得数据写入到word文件中
            strContent = "\r\n ";
            WordDoc.Paragraphs.Last.Range.Text = strContent;
            #endregion
            return WordDoc;

        }
        private void SaveWord(ref Document WordDoc, string filename)
        {
            Object oMissing = System.Reflection.Missing.Value;
            Object strFileName = (Object)filename;
            //将WordDoc文档对象的内容保存为DOC文档   
            WordDoc.SaveAs(ref strFileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref   oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            //关闭WordDoc文档对象   
            WordDoc.Close(ref oMissing, ref oMissing, ref oMissing);

        }
        public static void OpenWord(string filename)
        {
            if (File.Exists(filename))
            {
                object oMissing = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Word._Application oWord;
                Microsoft.Office.Interop.Word._Document oDoc;
                oWord = new Microsoft.Office.Interop.Word.Application();
                oWord.Visible = true;
                object fileName = filename;
                try
                {
                    oDoc = oWord.Documents.Open(ref fileName,
    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                }
                catch (Exception e)
                {
                    if (DialogResult.Retry == MessageBox.Show(e.Message, "打开失败", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error))
                    {
                        KillWordProcess();
                        OpenWord(filename);
                    };
                    return;
                }

            }
            else
            {
                MessageBox.Show(filename + "\r\n不存在!", "确认路径!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private void SaveTabDesc()
        {
            if (!ValidTable()) return;
            if (!sif.DataSource)
            {
                if (!dic.ContainsKey(userControl11.MyText))
                {
                    SetStatus("数据库未连接,无法保存表描述!");
                    return;
                }
            }
            if (dic[userControl11.MyText].ContainsKey(comboBox1.Text) && dic[userControl11.MyText][comboBox1.Text].Description != GetTabDescByTextBox())
                SaveTabDescription();


        }
        private void AutoSaveTabDesc()
        {
            if (checkBox1.Checked)
                SaveTabDesc();
        }
        private void ShowHelp()
        {
            MessageBox.Show(Resources.String1, "快捷键提示!", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        private bool ProcessKeyEvent(KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F12)
            {
                textBox1_KeyDown(textBox1, new KeyEventArgs(Keys.Down));
                return true;
            }
            else if (e.KeyCode == Keys.F11)
            {
                textBox1_KeyDown(textBox1, new KeyEventArgs(Keys.Up));
                return true;
            }
            else if ((e.KeyCode == Keys.F1 && !e.Control) || (e.KeyCode == Keys.H && e.Control))
            {
                ShowHelp();
                return true;
            }
            else if (e.KeyCode == Keys.F2)
            {
                checkBox1.Checked = !checkBox1.Checked;
                return true;
            }
            else if (e.KeyCode == Keys.F3)
            {
                GetOneTabCode();
                return true;
            }
            else if (e.KeyCode == Keys.F4)
            {
                GetAllTabCode();
                return true;
            }
            else if (e.KeyCode == Keys.F6)
            {
                button3_Click(button3, null);
                return true;
            }
            else if (e.KeyCode == Keys.F7)
            {
                button2_Click(button2, null);
                return true;
            }
            else if (e.KeyCode == Keys.F8)
            {
                f2.ShowDialog();
                return true;
            }
            else if (e.KeyCode == Keys.F9)
            {
                button11_Click(button11, null);
                return true;
            }
            else if (e.KeyCode == Keys.F10)
            {
                button12_Click(button12, null);
                return true;
            }
            else if (e.KeyCode == Keys.F5 && (e.Control || e.Shift))
            {
                if (!choseFile1.IsValid())
                {
                    MessageBox.Show("数据源文件格式不正确!", "确认文件格式", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    SetStatus("数据源文件格式不正确!");
                    return true;

                }
                isRefreashing = true;
                KillWordProcess();
                Thread t = new Thread(GetWordDataSource);
                t.Start();
                return true;
            }
            else if (e.KeyCode == Keys.F5)
            {
                if (RefreashData())
                    SetStatus("数据已刷新!");
                else
                {
                    SetStatus("数据刷新失败,请检查连接!");
                }
                return true;
            }
            else if ((e.KeyCode == Keys.T || e.KeyCode == Keys.D) && e.Control)
            {
                bool show = radioButton4.Checked;
                radioButton4.Checked = !show;
                radioButton5.Checked = show;
                SetStatus("数据源切换成功!");
                return true;
            }
            else if (e.KeyCode == Keys.Q && e.Control)
            {
                Process.GetCurrentProcess().Kill();
                return true;
            }
            else if (e.KeyCode == Keys.S && e.Control && e.Shift)
            {
                SaveTabToTab();
                return true;
            }
            else if (e.KeyCode == Keys.S && e.Control)
            {
                SaveAll();
                return true;
            }
            else if (e.KeyCode == Keys.P && e.Control)
            {
                isStopConvert = true;
                return true;
            }
            else if ((e.KeyCode == Keys.F1 && e.Control) || e.KeyCode == Keys.Pause)
            {
                TestConnect();
                return true;
            }
            return false;
        }
        private void SaveColsToDb(string colstr, string coldesc)
        {

            if (dic.ContainsKey(userControl11.MyText))
            {
                SetText("正在批量保存字段描述到数据库...");
                int i = 0;
                try
                {
                    if (colstr != "")
                        foreach (KeyValuePair<string, TableInfo> ti in dic[userControl11.MyText])
                        {

                            if (dic[userControl11.MyText].ContainsKey(ti.Key))
                            {
                                dic[userControl11.MyText][ti.Key].Description = ti.Value.Description;
                                DataTable dt = ti.Value.dt;

                                i++;


                                if (dt == null)
                                {
                                    dt = GetColumnsDesc(ti.Key, true);
                                    dic[userControl11.MyText][ti.Key].dt = dt;
                                }
                                foreach (DataRow item in dt.Rows)
                                {
                                    string col_name = item.ItemArray[0].ToString();
                                    if (col_name != colstr) continue;
                                    string col_type = "";
                                    SaveColDescriptionByInfo(ti.Key, colstr, coldesc, col_type);
                                }
                                SetStatus(i.ToString() + " -- " + ti.Key + " 已保存!");
                            }
                        }
                }
                catch (Exception e)
                {
                    SetText("发生异常!");
                    SetStatus(e.Message);
                }
                SetText("批量保存字段描述到数据库已完成!");
            }
            else
                SetText("数据不完整,无法保存!");
        }
        bool SaveAllDescInstance = false;
        private void SaveTabToTab()
        {

            if (dic.ContainsKey(userControl11.MyText) && dic.ContainsKey(choseFile1.MyText))
            {
                SetText("正在保存文件描述到数据库...");
                int i = 0;
                try
                {
                    if (RaidoIsAccess == false) SaveAllDescInstance = true;
                    Dictionary<string, TableInfo> tit = new Dictionary<string, TableInfo>(dic[choseFile1.MyText]);
                    foreach (KeyValuePair<string, TableInfo> ti in tit)
                    {

                        if (dic[userControl11.MyText].ContainsKey(ti.Key))
                        {
                            dic[userControl11.MyText][ti.Key].Description = ti.Value.Description;
                            SaveTabDescription(ti.Key, ti.Value.Description);
                            DataTable dt = ti.Value.dt;
                            i++;
                            foreach (DataRow item in dt.Rows)
                            {
                                string col_name = item.ItemArray[0].ToString();
                                SaveColDescriptionByInfo(ti.Key, item.ItemArray[0].ToString(), item.ItemArray[4].ToString());
                            }
                            SetStatus(i.ToString() + " -- " + ti.Key + " 已保存!");
                        }
                    }
                }
                catch (Exception e)
                {
                    SetText("发生异常!");
                    SetStatus(e.Message);
                }
                SetText("保存文件描述到数据库已完成!");
            }
            else
                SetText("数据不完整,无法保存!");
        }
        bool isRefreashing = false;
        bool isStopConvert = false;
        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {

            TextBox tb = (TextBox)sender;
            if (e.KeyCode == Keys.Enter)
            {
                SaveTabDesc();
            }
            if (!ValidTable()) return;
            if (e.KeyCode == Keys.Down)
            {

                string[] strs = GetComBoBoxData();
                bool f = false;
                foreach (var item in strs)
                {
                    if (item == comboBox1.Text)
                    {
                        f = true; continue;
                    }
                    if (f)
                    {
                        AutoSaveTabDesc();
                        comboBox1.Text = item;
                        tb.SelectionStart = tb.Text.Length;

                        return;
                    }

                }
            }
            else if (e.KeyCode == Keys.Up)
            {

                string[] strs = GetComBoBoxData();

                string pre = "";
                foreach (var item in strs)
                {

                    if (pre != "" && item == comboBox1.Text)
                    {
                        AutoSaveTabDesc();
                        comboBox1.Text = pre;
                        tb.SelectionStart = tb.Text.Length;
                        return;
                    }
                    pre = item;
                }


            }
        }

        private void textBox1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Down)
            {
                TextBox tb = (TextBox)sender;
                tb.SelectionStart = tb.Text.Length;
            }
            else if (e.KeyCode == Keys.Up)
            {
                TextBox tb = (TextBox)sender;
                tb.SelectionStart = 0;
            }
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Process.GetCurrentProcess().Kill();
        }
        private void SaveCurrColDesc(DataGridViewRow dgvr)
        {
            if (!ValidTable()) return;
            if (!sif.DataSource)
            {
                if (!dic.ContainsKey(userControl11.MyText))
                {
                    SetStatus("数据库未连接,无法保存字段描述!");
                    return;
                }
            }
            if (!dic[userControl11.MyText].ContainsKey(comboBox1.Text))
            {
                SetStatus("数据库未找到表" + comboBox1.Text + ",请刷新重试!");
                return;
            }

            if (dic[userControl11.MyText][comboBox1.Text].dt == null)
            {
                dic[userControl11.MyText][comboBox1.Text].dt = GetColumnsDesc(comboBox1.Text, true);
            }
            DataTable dt = dic[userControl11.MyText][comboBox1.Text].dt;

            bool flag = false;
            foreach (DataRow item in dt.Rows)
            {
                if (item.ItemArray[0].ToString() == dgvr.Cells[1].Value.ToString())
                {
                    flag = true;
                    break;
                }
            }
            if (!flag)
            {
                SetStatus("数据库未找到字段" + dgvr.Cells[1].Value.ToString() + "!");
                return;
            }

            string dicdesc = dic[userControl11.MyText][comboBox1.Text].dt.Rows[dgvr.Index].ItemArray[4].ToString();
            if (dgvr.Cells[5].Value == null) dgvr.Cells[5].Value = "";
            if (dgvr.Cells[0].Value == null) dgvr.Cells[0].Value = "";
            if (dicdesc.Contains(";"))
            {
                string c0 = dicdesc.Split(';')[0];
                int sta = dicdesc.IndexOf(';');
                string c5 = "";
                if (sta != -1) c5 = dicdesc.Substring(sta + 1);
                if (c5 == dgvr.Cells[5].EditedFormattedValue.ToString() && c0 == dgvr.Cells[0].EditedFormattedValue.ToString()) return;
            }
            string colstr = dgvr.Cells[1].Value.ToString();//(string)dic[userControl11.MyText][comboBox1.Text].dt.Rows[dgvr.Index].ItemArray[0];

            string coltyp = "";
            if (sif.DataBaseType == 0 && dgvr.Index < dic[userControl11.MyText][comboBox1.Text].dt.Rows.Count && dic[userControl11.MyText][comboBox1.Text].dt.Rows[dgvr.Index].ItemArray[0].ToString() == dgvr.Cells[1].Value.ToString())
                coltyp = (string)dic[userControl11.MyText][comboBox1.Text].dt.Rows[dgvr.Index].ItemArray[1];// dgvr.Cells[2].Value.ToString();



            if (dgvr.Cells[0].Value.ToString() == dgvr.Cells[5].Value.ToString())
            {
                if (dicdesc != dgvr.Cells[5].Value.ToString())
                {
                    SaveColDescriptionByInfo(comboBox1.Text, colstr, dgvr.Cells[5].Value.ToString(), coltyp);
                    object[] objs = dic[userControl11.MyText][comboBox1.Text].dt.Rows[dgvr.Index].ItemArray;
                    objs[4] = dgvr.Cells[5].Value;
                    dic[userControl11.MyText][comboBox1.Text].dt.Rows[dgvr.Index].ItemArray = objs;
                    dic[userControl11.MyText][comboBox1.Text].dt.Rows[dgvr.Index].ItemArray[4] = dgvr.Cells[5].Value;
                }
            }
            else
            {
                string restore = dgvr.Cells[0].EditedFormattedValue + ";" + dgvr.Cells[5].EditedFormattedValue;
                restore = restore.TrimStart(';');
                if (dicdesc != restore)
                {
                    SaveColDescriptionByInfo(comboBox1.Text, colstr, restore, coltyp);
                    object[] objs = dic[userControl11.MyText][comboBox1.Text].dt.Rows[dgvr.Index].ItemArray;
                    objs[4] = restore;
                    dic[userControl11.MyText][comboBox1.Text].dt.Rows[dgvr.Index].ItemArray = objs;
                }
            }
        }

        private void SaveColDescriptionByInfo(string table, string column, string col_desc, string coltype = "")
        {
            string altstr = "";
            string[] strs = col_desc.Split(';');
            if (strs.Length == 2)
            {
                if (strs[0] == strs[1]) col_desc = strs[0];
            }
            switch (sif.DataBaseType)
            {
                case 0:
                    altstr = "alter table {0} modify column {1} {2} comment '{3}'";
                    break;
                case 1:
                    altstr = "COMMENT ON COLUMN {0}.{1} is '{2}'";
                    break;
                case 2:
                    string name = "'MS_Description',";
                    string str = "'user','dbo','table','{0}','column','{1}'";
                    altstr = "if (SELECT count(*) FROM ::fn_listextendedproperty (" + name + str + "))> 0 begin EXECUTE sp_updateextendedproperty " + name + "'{2}'," + str + ";end else begin EXECUTE sp_addextendedproperty " + name + "'{2}'," + str + ";end;";

                    break;
                default:
                    break;
            }
            switch (sif.DataBaseType)
            {
                case 0:
                    if (coltype == "")
                    {
                        DataTable dt1 = null;
                        if (dic[userControl11.MyText].ContainsKey(table))
                            dt1 = dic[userControl11.MyText][table].dt;
                        else
                        {
                            dic[userControl11.MyText][table] = new TableInfo(table);
                            dic[userControl11.MyText][table].Description = GetTableDesc(table, true, true);
                        }
                        if (dt1 == null)
                        {
                            dt1 = GetColumnsDesc(table, true);
                            dic[userControl11.MyText][table].dt = dt1;
                        }
                        DataRow[] drs = dt1.Select(dt1.Columns[0].ColumnName + "='" + column + "'");
                        if (drs.Length != 1) return;
                        coltype = drs[0].ItemArray[1].ToString();
                    }
                    altstr = string.Format(altstr, table, column, coltype, col_desc.Replace("'", "''"));
                    break;
                case 1:
                    altstr = string.Format(altstr, table, column, col_desc.Replace("'", "''"));
                    break;
                case 2:
                    altstr = string.Format(altstr, table, column, col_desc.Replace("'", "''"));
                    try
                    {
                        SqlConnection sqlCon = new SqlConnection(userControl11.MyText);
                        SqlCommand sqlCmd = new SqlCommand("sp_executesql", sqlCon);
                        sqlCmd.CommandType = CommandType.StoredProcedure;//设置调用的类型为存储过程  

                        SqlParameter sqlParme;
                        sqlParme = sqlCmd.Parameters.Add("@sql", SqlDbType.NVarChar, 5000);
                        sqlParme.Direction = ParameterDirection.Input;
                        sqlParme.Value = altstr;
                        sqlCon.Open();
                        sqlCmd.ExecuteNonQuery();
                        sqlCon.Close();
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message, "修改字段描述发生异常", MessageBoxButtons.OK, MessageBoxIcon.Error); ;
                    }
                    break;
                default:
                    break;
            }
            SaveColDescription(altstr, column, table);

        }
        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            DataGridView dgv = (DataGridView)sender;
            DataGridViewRow dgvr = dgv.CurrentCell.OwningRow;
            if ((dgv.CurrentCell.ColumnIndex == 0 || dgv.CurrentCell.ColumnIndex == 5) && checkBox1.Checked) SaveCurrColDesc(dgvr);

        }

        private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
        {

            DataGridView dgv = (DataGridView)sender;
            DataGridViewRow dgvr = dgv.CurrentCell.OwningRow;
            if (dgv.Focused && (dgv.CurrentCell.ColumnIndex == 5 || dgv.CurrentCell.ColumnIndex == 0))
            {
                dgv.BeginEdit(true);
            }

        }

        private void button8_Click(object sender, EventArgs e)
        {
            GetOneTabCode();
        }
        private void GetAllTabCode()
        {
            if (!ValidTable()) return;
            SetStatus("正在获取建库脚本.....");
            string[] tabs = new string[0];
            string codes = "";
            string path = TempTxtPath + ".sql";
            if (sif.DataSource)
                switch (sif.DataBaseType)
                {
                    case 0:
                        tabs = ReadMyData("show tables");
                        if (tabs != null)
                        {
                            for (int i = 0; i < tabs.Length; i++)
                            {
                                string[] strs = ReadMyData("show create table " + tabs[i]);
                                if (strs != null)
                                {
                                    if (i != 0) codes += "\r\n\r\n";
                                    codes += strs[1];
                                    codes += ";";
                                }

                            }
                        }
                        break;
                    case 1:
                        tabs = ReadMyData("select DBMS_LOB.substr(DBMS_METADATA.get_ddl('TABLE',u.TABLE_NAME)) a FROM USER_TABLES U");
                        for (int i = 0; i < tabs.Length; i++)
                        {
                            if (i != 0) codes += "\r\n\r\n";
                            codes += tabs[i];
                            codes += ";";
                        }
                        break;
                    case 2:

                        SetStatus("暂不支持sqlserver!");
                        return;
                    default:
                        break;
                }
            else
            {

                codes = GetSortCreateTableByKey();
            }



            if (codes != "")
            {
                MyClass.WriteFile(path, codes);
                SetStatus("建库脚本获取成功!");
                Process.Start("notepad", path);
            }
            else
            {
                SetStatus("未发现建库脚本!");
            }

        }
        private string GetSortCreateTableByKey()
        {
            Dictionary<string, TableInfo> dics = dic[choseFile1.MyText];
            List<string> strls = new List<string>();
            List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
            string codes = "";
            foreach (KeyValuePair<string, TableInfo> item in dics)
            {
                if (!strls.Contains(item.Key))
                {
                    strls.Add(item.Key);
                    string strs = GetFileCreateTable(item.Key);
                    if (strs != "")
                    {
                        strs += ";\r\n";
                        KeyValuePair<string, string> kvp = new KeyValuePair<string, string>(item.Key, strs);
                        list.Add(kvp);
                    }
                    string LatTable = item.Key;
                    string ForTable = GetForignKey(item.Key);
                    while (ForTable != "")
                    {
                        if (!strls.Contains(ForTable))
                        {
                            strls.Add(ForTable);
                            strs = GetFileCreateTable(ForTable);
                            if (strs != "")
                            {
                                strs += ";\r\n";
                                int i = 0;
                                foreach (KeyValuePair<string, string> sitem in list)
                                {
                                    if (sitem.Key == LatTable) break;
                                    i++;
                                }
                                list.Insert(i, new KeyValuePair<string, string>(ForTable, strs));
                                LatTable = ForTable;
                                ForTable = GetForignKey(ForTable);
                            }
                        }
                        else break;
                    }
                }
            }
            foreach (KeyValuePair<string, string> sitem in list)
            {
                codes += sitem.Value;
            }
            return codes;
        }
        private string GetForignKey(string TableName)
        {
            DataTable dt = GetColumnsDesc(TableName, sif.DataSource);
            string ForTable = "";
            if (dt != null)
            {
                for (int i = 0; i < dt.Rows.Count; i++)// item in dt.Rows)
                {
                    string col_name = dt.Rows[i].ItemArray[0].ToString().Trim();
                    if (dt.Rows[i].ItemArray[3].ToString().Trim() == "外键")
                    {
                        foreach (KeyValuePair<string, TableInfo> item in dic[choseFile1.MyText])
                        {
                            DataTable idt = item.Value.dt;
                            for (int j = 0; j < idt.Rows.Count; j++)
                            {
                                if (idt.Rows[j].ItemArray[0].ToString().Trim() == col_name)
                                    if (item.Key != TableName && idt.Rows[j].ItemArray[3].ToString().Trim() == "主键")
                                    {
                                        ForTable = item.Key;
                                        break;
                                    }
                            }

                        }
                    }
                }
            }
            return ForTable;
        }
        private void GetOneTabCode()
        {
            if (ValidTable())
            {
                SetStatus("正在获取建库脚本.....");
                string path = TempTxtPath + ".sql";
                string[] strs = new string[0];
                if (sif.DataSource)
                    switch (sif.DataBaseType)
                    {
                        case 0:
                            strs = ReadMyData("show create table " + comboBox1.Text); ;
                            break;
                        case 1:
                            strs = ReadMyData("select table_name,DBMS_LOB.substr(DBMS_METADATA.get_ddl('TABLE',u.TABLE_NAME)) a FROM USER_TABLES U  where u.table_name='" + comboBox1.Text + "'");
                            break;
                        case 2:
                            SetStatus("暂不支持sqlserver!");
                            return;
                        default:
                            break;
                    }
                else
                {
                    string str = GetFileCreateTable(comboBox1.Text);
                    if (str != "")
                    {
                        strs = new string[2];
                        strs[1] = str;
                    }
                }
                if (strs != null && strs.Length == 2)
                {
                    MyClass.WriteFile(path, strs[1] + ";");
                    SetStatus("建库脚本获取成功!");
                    Process.Start("notepad", path);
                }
                else
                {
                    SetStatus("未发现建库脚本!");
                }
            }
        }

        private string GetFileCreateTable(string TableName)
        {
            DataTable dt = GetColumnsDesc(TableName, sif.DataSource);
            string TableSpace = "";
            if (checkBox2.Checked)
            {
                TableSpace = textBox4.Text.Trim();
            }
            if (TableSpace != "") TableSpace += ".";
            string str = "";
            string primforistr = "";
            if (dt != null)
            {
                str = "CREATE TABLE {0}" + TableName + " (";
                for (int i = 0; i < dt.Rows.Count; i++)// item in dt.Rows)
                {
                    if (i != 0 && i != dt.Rows.Count) str += ",";
                    string nulstr = "";
                    string liter = dt.Rows[i].ItemArray[2].ToString().Trim();
                    string col_name = dt.Rows[i].ItemArray[0].ToString().Trim();
                    if (liter == "否" || liter.ToUpper() == "NO")
                        nulstr = " NOT NULL";
                    str += string.Format("\r\n {0} {1}{2}", col_name
                         , dt.Rows[i].ItemArray[1].ToString().Trim()
                         , nulstr);

                    if (dt.Rows[i].ItemArray[3].ToString().Trim() == "主键")
                    {
                        primforistr += ",";
                        primforistr += string.Format("\r\n CONSTRAINT {1}_{0}_P PRIMARY KEY ({2})", GetRemovePre(col_name), GetRemovePre(TableName), col_name);

                    }

                    if (dt.Rows[i].ItemArray[3].ToString().Trim() == "外键")
                    {

                        string fkeys = "\r\n  CONSTRAINT {2}_{3}_F FOREIGN KEY ({0}) REFERENCES {{0}}{1} ({0})";
                        string ftab = "";

                        foreach (KeyValuePair<string, TableInfo> item in dic[choseFile1.MyText])
                        {
                            DataTable idt = item.Value.dt;
                            for (int j = 0; j < idt.Rows.Count; j++)
                            {
                                if (idt.Rows[j].ItemArray[0].ToString().Trim() == col_name)
                                    if (item.Key != TableName && idt.Rows[j].ItemArray[3].ToString().Trim() == "主键")
                                    {
                                        ftab = item.Key;
                                        break;
                                    }
                            }
                            if (ftab != "") break;
                        }
                        if (ftab == "")
                        {
                            ftab = "ForignTable";
                        }
                        primforistr += ",";
                        primforistr += string.Format(fkeys, col_name, ftab, GetRemovePre(TableName), GetRemovePre(col_name));


                    }

                }
                str += primforistr + "\r\n)";
                str = string.Format(str, TableSpace);


            }
            return str;
        }
        private string GetRemovePre(string name)
        {
            int index = name.IndexOf("_");
            return name.Substring(index + 1);
        }
        private void button9_Click(object sender, EventArgs e)
        {
            SetText("脚本正在生成...");
            ((Button)(sender)).Enabled = false;
            GetAllTabCode();
            ((Button)(sender)).Enabled = true;
            SetText("脚本已生成!");
        }



        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (ProcessKeyEvent(e)) return;
        }



        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            System.Windows.Forms.CheckBox cb = (System.Windows.Forms.CheckBox)sender;
            sif.isAutoSave = cb.Checked;
            SaveProfile(true);
            SetSetingStatus();
        }


        public void SetSetingStatus()
        {
            string str = "\t";
            str += "数据源:";
            if (sif.DataSource) str += "数据库"; else str += "文件";
            str += ";自动提交:";
            if (sif.isAutoSave) str += "On"; else str += "Off";
            str += ";自动保存:";
            if (sif.isAutoSetting) str += "On"; else str += "Off";
            toolStripStatusLabel2.Text = str;
        }

        SettingInfo sif = new SettingInfo();
        private void Test()
        {
            SqlConnection conn = new SqlConnection("server=192.168.234.128;database=Test;uid=sa;pwd=123");
            SqlDataAdapter sda = new SqlDataAdapter("select name from sys.tables", conn);
            DataSet ds = new DataSet();
            sda.Fill(ds, "Table_1");
            dataGridView1.DataSource = ds.Tables[0];
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            IntPtr sysMenuHandle = GetSystemMenu(this.Handle, false);

            InsertMenu(sysMenuHandle, 5, MF_BYPOSITION | MF_SEPARATOR, 0, string.Empty);
            //加入自定义的菜单项  
            InsertMenu(sysMenuHandle, 6, MF_BYPOSITION, IDM_HELP, "帮助(&H)");
            //Test();
            SetSetingStatus();
            IniSeting();
            TestConnect();
            if (comboBox1.Items.Count != 0)
            {
                comboBox1.Text = comboBox1.Items[0].ToString();
            }
        }
        private void IniSeting()
        {
            switch (sif.DataBaseType)
            {
                case 0:
                    radioButton1.Checked = true;
                    break;
                case 1:
                    radioButton2.Checked = true;
                    break;
                case 2:
                    radioButton3.Checked = true;
                    break;
                default:
                    break;
            }
            tabControl1.SelectedIndex = sif.TabSelIndex;
            checkBox1.Checked = sif.isAutoSave;
            radioButton5.Checked = sif.DataSource;
            checkBox3.Checked = sif.isAutoSetting;
            choseFile1.MyText = sif.input;
            choseFile2.MyText = sif.output;
            choseFile1.save += MyChoseFile_TextChanged;
            choseFile1.save += sif.SaveToFile;
            choseFile2.save += MyChoseFile_TextChanged;
            choseFile2.save += sif.SaveToFile;
        }
        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            TabControl tc = (TabControl)sender;
            sif.TabSelIndex = tc.SelectedIndex;
            SaveProfile(true);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (ValidTable())
            {
                if (CheckDocValid(true))
                {
                    MyChoseFile_TextChanged();

                    if (dic.ContainsKey(DisplayDataString))
                    {
                        if (dic[DisplayDataString].ContainsKey(comboBox1.Text))
                        {
                            ((Button)sender).Enabled = false;
                            string str = GetTableDesc(comboBox1.Text);
                            string[] strs = GetTabDescToArray(str);
                            dic[DisplayDataString][comboBox1.Text].Description = str;
                            TabIns[0] = strs[0];
                            TabIns[1] = comboBox1.Text;
                            TabIns[2] = strs[1];
                            TabIns[3] = strs[2];
                            Thread t = new Thread(ConvertOneToWord);
                            t.Start();
                            return;
                        }
                        else
                        {
                            MessageBox.Show("发生错误,该表未找到!", "表未找到", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    else
                    {
                        MessageBox.Show("请测试连接,或载入数据!", "数据载入出错", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }

        }
        private void ConvertOneToWord()
        {
            try
            {
                // KillWordProcess();
                OutPutOneDBDoc(choseFile2.MyText);
                button3.BeginInvoke(new SetConBol(SetBtn3), new object[] { true });
            }
            catch (Exception)
            {


            }

        }
        private string[] TabIns = new string[4];
        public void OutPutOneDBDoc(string output)
        {
            Object oMissing = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
            Microsoft.Office.Interop.Word.Document WordDoc2 = WordApp.Documents.Open(output);

            string fileName = MyClass.TempFile + ".doc";
            Microsoft.Office.Interop.Word.Document OutWordDoc = CreateWord(fileName);
            object strFileName = fileName;
            OutWordDoc.SaveAs(ref strFileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref   oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

            List<object> po = new List<object>();
            po.Add(TabIns[0]);
            po.Add(TabIns[1]);
            po.Add(TabIns[2]);
            DataTable dt1 = dic[DisplayDataString][TabIns[1]].dt;
            if (dt1 == null)
            {
                dt1 = GetColumnsDesc(TabIns[1], true);
                dic[DisplayDataString][TabIns[1]].dt = dt1;
            }
            po.Add(dt1);
            po.Add(TabIns[3]);

            //  for (int x = 1; x <= TotleCount; x++)


            //进行条件筛选
            if (checkBox2.Checked)
            {
                bool flag = false;
                foreach (DataRow dr in dt1.Rows)
                {
                    if (dr.ItemArray[0].ToString().Contains(textBox4.Text))
                    {
                        flag = true;
                    }
                }
                if (!flag)
                {
                    SetStatus("该表未满足过滤条件!");
                    return;
                }
            }
            //if (!tTs[x].Range.Text.Contains("latitude")) continue;

            //全选模板并复制
            //Table t1 = WordDoc2.Tables[1];
            Range wr1 = WordDoc2.Range(0, WordDoc2.Tables[1].Range.End);
            wr1.Select();
            wr1.Copy();

            //确定输出位置并粘贴
            Range wr = OutWordDoc.Range(0);
            wr.Paste();

            Table mT = OutWordDoc.Tables[1];

            //确定标题常量

            int index = 1;
            object sta = 0;
            object end = mT.Range.Start - 1;

            //确定修改范围
            Range wr3 = OutWordDoc.Range(sta, end);
            string c = Trim(wr3.Text);
            wr3.Text = wr3.Text.Replace("{0}", po[0].ToString()).Replace("{i}", index.ToString());

            //Console.WriteLine(wr3.Text);
            SetStatus(wr3.Text + " -- " + po[1].ToString() + " 已生成!");

            //wr3.Font = font;
            //wr3.Font.Name = "微软雅黑";
            #region 循环行
            int mTRowsCount = mT.Rows.Count;
            for (int i = 1; i <= mTRowsCount; i++)
            {
                int mTRowsiCellsCount = mT.Rows[i].Cells.Count;
                #region 数组情况
                if (mT.Cell(i, 1).Range.Text.Contains("}["))
                {
                    // string rowstr = "";
                    string colstr = "";

                    /* int i1 = content.IndexOf("{");
                       int i2 = content.IndexOf("}");
                       if (!(i1 == -1 || i2 == -1))
                        rowstr = content.Substring(i1 + 1, i2 - i1 - 1);
                       */
                    DataTable dt = (DataTable)po[3];
                    for (int k = 0; k < dt.Rows.Count; k++)
                    {

                        for (int j = 1; j <= mTRowsiCellsCount; j++)
                        {
                            if (k != dt.Rows.Count - 1 && j == 1)
                            {
                                object beforeRow = mT.Rows[i + k];
                                mT.Rows.Add(ref beforeRow);
                                mTRowsCount++;
                                // mT.Cell(i + k + 1, j).Range.Shading.BackgroundPatternColor = mT.Cell(i, j).Range.Shading.BackgroundPatternColor;
                                //mT.Cell(i + k + 1, j).Range.Text = mT.Cell(i, j).Range.Text;
                            }
                            string content = Trim(k != dt.Rows.Count - 1 ? mT.Cell(i + k + 1, j).Range.Text : mT.Cell(i + k, j).Range.Text);
                            int i1 = content.IndexOf("[");
                            int i2 = content.IndexOf("]");
                            if (!(i1 == -1 || i2 == -1))
                                colstr = content.Substring(i1 + 1, i2 - i1 - 1);
                            int col = Int32.Parse(colstr) - 2;
                            if (col == -1)
                            {
                                string str = dt.Rows[k].ItemArray[4].ToString();
                                mT.Cell(i + k, j).Range.Text = str.Split(';')[0];
                            }
                            else if (col == 4)
                            {
                                string str = dt.Rows[k].ItemArray[4].ToString();
                                int dots = str.IndexOf(';');
                                mT.Cell(i + k, j).Range.Text = str.Substring(dots + 1);
                            }
                            else
                            {
                                string strcol = dt.Rows[k].ItemArray[col].ToString();
                                mT.Cell(i + k, j).Range.Text = strcol;
                            }
                        }
                    }
                    continue;
                }
                #endregion
                else
                {
                    for (int j = 1; j <= mTRowsiCellsCount; j++)
                    {
                        string str = Trim(mT.Cell(i, j).Range.Text);
                        int i1 = str.IndexOf("{");
                        int i2 = str.IndexOf("}");
                        string icount = "";
                        if (!(i1 == -1 || i2 == -1))
                            icount = str.Substring(i1 + 1, i2 - i1 - 1);
                        try
                        {
                            int col = Int32.Parse(icount);
                            if (col < 0 || col > 4)
                            {
                                SetStatus("模板格式错误,单元格位置:" + i + "," + j);
                                continue;
                            }
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                        str = string.Format(str, po[0], po[1], po[2], po[3], po[4]);
                        mT.Cell(i, j).Range.Text = str;
                    }
                }
            }
            #endregion
            OutWordDoc.Save();
            // KillWordProcess();
            WordDoc2.Close();
            OutWordDoc.Close();
            WordApp.Visible = true;
            try
            {
                WordApp.Documents.Open(ref strFileName,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            }
            catch (Exception)
            {

            }


            // OpenWord(fileName);
        }
        public void OutPutAllDBDoc(string output)
        {
            Object oMissing = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
            Microsoft.Office.Interop.Word.Document WordDoc2 = WordApp.Documents.Open(output);

            string fileName = MyClass.TempFile + ".doc";
            Microsoft.Office.Interop.Word.Document OutWordDoc = CreateWord(fileName);
            object strFileName = fileName;
            OutWordDoc.SaveAs(ref strFileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref   oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            int index = 1;
            foreach (KeyValuePair<string, TableInfo> item in dic[DisplayDataString])
            {
                if (banch)
                {
                    SetStatus("任务已取消...");
                    banch = false;
                    KillWordProcess();
                    OpenWord(fileName);
                    return;
                }
                if (item.Value.dt == null)
                {
                    dic[userControl11.MyText][item.Key].Description = GetTableDesc(item.Key);
                    dic[userControl11.MyText][item.Key].dt = GetColumnsDesc(item.Key, true);
                }
                if (checkBox2.Checked)
                {
                    bool flag = false;
                    foreach (DataRow itemr in item.Value.dt.Rows)
                    {
                        if (itemr.ItemArray[0].ToString().Contains(textBox4.Text))
                            flag = true;
                    }
                    if (!flag) continue;
                }
                string[] rts = GetTabDescToArray(item.Value.Description);
                List<object> po = new List<object>();
                po.Add(rts[0]);
                po.Add(item.Key);
                po.Add(rts[1]);
                po.Add(item.Value.dt);
                po.Add(rts[2]);

                //全选模板并复制
                //Table t1 = WordDoc2.Tables[1];
                Range wr1 = WordDoc2.Range(0, WordDoc2.Tables[1].Range.End);
                wr1.Select();
                wr1.Copy();

                //确定输出位置并粘贴
                Range wr = OutWordDoc.Range(OutWordDoc.Content.End - 1 < 0 ? 0 : OutWordDoc.Content.End - 1);
                wr.Paste();

                Table mT = OutWordDoc.Tables[OutWordDoc.Tables.Count];

                //确定标题常量


                object sta = index == 1 ? 0 : OutWordDoc.Tables[index - 1].Range.End;
                object end = mT.Range.Start - 1;

                //确定修改范围
                Range wr3 = OutWordDoc.Range(sta, end);
                string c = Trim(wr3.Text);
                wr3.Text = c.Replace("{0}", po[0].ToString()).Replace("{i}", index.ToString());

                //Console.WriteLine(wr3.Text);
                SetStatus(wr3.Text + " -- " + po[1].ToString() + " 已生成!");
                index++;
                //wr3.Font = font;
                //wr3.Font.Name = "微软雅黑";
                #region 循环行
                int mTRowsCount = mT.Rows.Count;
                for (int i = 1; i <= mTRowsCount; i++)
                {
                    int mTRowsiCellsCount = mT.Rows[i].Cells.Count;
                    #region 数组情况
                    if (mT.Cell(i, 1).Range.Text.Contains("}["))
                    {
                        // string rowstr = "";
                        string colstr = "";

                        /* int i1 = content.IndexOf("{");
                           int i2 = content.IndexOf("}");
                           if (!(i1 == -1 || i2 == -1))
                            rowstr = content.Substring(i1 + 1, i2 - i1 - 1);
                           */
                        DataTable dt = (DataTable)po[3];
                        for (int k = 0; k < dt.Rows.Count; k++)
                        {

                            for (int j = 1; j <= mTRowsiCellsCount; j++)
                            {
                                if (k != dt.Rows.Count - 1 && j == 1)
                                {
                                    object beforeRow = mT.Rows[i + k];
                                    mT.Rows.Add(ref beforeRow);
                                    mTRowsCount++;
                                    // mT.Cell(i + k + 1, j).Range.Shading.BackgroundPatternColor = mT.Cell(i, j).Range.Shading.BackgroundPatternColor;
                                    //mT.Cell(i + k + 1, j).Range.Text = mT.Cell(i, j).Range.Text;
                                }
                                string content = Trim(k != dt.Rows.Count - 1 ? mT.Cell(i + k + 1, j).Range.Text : mT.Cell(i + k, j).Range.Text);
                                int i1 = content.IndexOf("[");
                                int i2 = content.IndexOf("]");
                                if (!(i1 == -1 || i2 == -1))
                                    colstr = content.Substring(i1 + 1, i2 - i1 - 1);
                                int col = Int32.Parse(colstr) - 2;
                                if (col == -1)
                                {
                                    string str = dt.Rows[k].ItemArray[4].ToString();
                                    mT.Cell(i + k, j).Range.Text = str.Split(';')[0];
                                }
                                else if (col == 4)
                                {
                                    string str = dt.Rows[k].ItemArray[4].ToString();
                                    int dots = str.IndexOf(';');
                                    mT.Cell(i + k, j).Range.Text = str.Substring(dots + 1);
                                }
                                else
                                {
                                    string strcol = dt.Rows[k].ItemArray[col].ToString();
                                    mT.Cell(i + k, j).Range.Text = strcol;
                                }
                            }
                        }
                        continue;
                    }
                    #endregion
                    else
                    {
                        for (int j = 1; j <= mTRowsiCellsCount; j++)
                        {

                            string str = Trim(mT.Cell(i, j).Range.Text);
                            int i1 = str.IndexOf("{");
                            int i2 = str.IndexOf("}");
                            string icount = "";
                            if (!(i1 == -1 || i2 == -1))
                                icount = str.Substring(i1 + 1, i2 - i1 - 1);
                            try
                            {
                                int col = Int32.Parse(icount);
                                if (col < 0 || col > 4)
                                {
                                    SetStatus("模板格式错误,单元格位置:" + i + "," + j);
                                    continue;
                                }
                            }
                            catch (Exception)
                            {
                                continue;
                            }
                            str = string.Format(str, po[0], po[1], po[2], po[3], po[4]);
                            mT.Cell(i, j).Range.Text = str;


                        }
                    }
                }
                #endregion


                OutWordDoc.Save();


            }
            OutWordDoc.Close();
            WordDoc2.Close();
            WordApp.Visible = true;
            try
            {
                WordApp.Documents.Open(ref strFileName,
 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            }
            catch (Exception)
            {


            }

            // KillWordProcess();
            // OpenWord(fileName);
        }
        public void ConvertWordFile(string input, string output)
        {

            Object oMissing = System.Reflection.Missing.Value;
            string dir = AppDomain.CurrentDomain.BaseDirectory;//System.Web.HttpContext.Current.Server.MapPath("");//首先在类库添加using System.web的引用

            Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
            //Microsoft.Office.Interop.Word.Document WordDoc = WordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            Microsoft.Office.Interop.Word.Document WordDoc = WordApp.Documents.Open(input);

            string fileName = MyClass.TempFile + ".doc";
            Microsoft.Office.Interop.Word.Document OutWordDoc = CreateWord(fileName);
            object strFileName = fileName;
            OutWordDoc.SaveAs(ref strFileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref   oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

            WordApp.ActiveWindow.View.Type = WdViewType.wdNormalView;
            #region 生成模板
            Dictionary<string, CellElement> Dic = new Dictionary<string, CellElement>();
            Tables tTs = WordDoc.Tables;
            {
                Table tT = WordDoc.Tables[1];
                int C = 1, A = 1;
                int ARow = 0;
                for (int i = 1; i <= tT.Rows.Count; i++)
                {
                    int ci = 0;
                    WdColor wcc = tT.Cell(i, 1).Range.Shading.BackgroundPatternColor;
                    for (int k = 1; k <= tT.Rows[i].Cells.Count; k++)
                    {
                        WdColor wci = tT.Cell(i, k).Range.Shading.BackgroundPatternColor;
                        if (wci == wcc && wcc != WdColor.wdColorGray125) { ci++; } else break;
                    }
                    if (ci == tT.Rows[i].Cells.Count)
                    {
                        if (ARow == i - 1)
                        {
                            ARow = i;
                            continue;
                        }
                        else
                        {
                            ARow = i;
                        }
                    }
                    for (int j = 1; j <= tT.Rows[i].Cells.Count; j++)
                    {

                        if (ci == tT.Rows[i].Cells.Count)
                        {
                            CellElement ce = new CellElement();
                            ce.point = new Point(i, 0);
                            ce.type = TypeOfElement.ARRAY;
                            Dic.Add("{" + A + "}[]", ce);
                            A++;
                            break;
                        }
                        else
                        {
                            WdColor wc = tT.Cell(i, j).Range.Shading.BackgroundPatternColor;
                            CellElement ce = new CellElement();
                            ce.point = new Point(i, j);
                            ce.obj = Trim(tT.Cell(i, j).Range.Text);
                            if (wc == WdColor.wdColorGray125)
                            {
                                ce.type = TypeOfElement.CONST;
                                Dic.Add("C" + C, ce);
                                C++;
                            }
                            else
                            {
                                ce.type = TypeOfElement.STRING;
                                Dic.Add("{" + A + "}", ce);
                                A++;
                            }

                        }
                    }
                }
            }
            #endregion

            SetStatus("模板生成成功!");

            Microsoft.Office.Interop.Word.Document WordDoc2 = WordApp.Documents.Open(output);
            Tables mTs = OutWordDoc.Tables;
            int TotleCount = WordDoc.Tables.Count;
            //object msta = 0;
            //object mend =WordDoc2.Tables[1].Range.Start;
            //Microsoft.Office.Interop.Word.Font font= WordDoc2.Range(msta, mend).Font;
            int index = 0;
            for (int x = 1; x <= TotleCount; x++)
            {
                if (!DToD) break;
                //进行条件筛选

                if (checkBox2.Checked)
                {
                    if (!tTs[x].Range.Text.Contains(textBox4.Text)) continue;
                }


                //全选模板并复制
                //Table t1 = WordDoc2.Tables[1];
                Range wr1 = WordDoc2.Range(0, WordDoc2.Tables[1].Range.End);
                wr1.Select();
                wr1.Copy();

                //确定输出位置并粘贴
                Range wr = OutWordDoc.Range(x == 1 ? 0 : OutWordDoc.Content.End - 1);
                wr.Paste();

                int Count = OutWordDoc.Tables.Count;
                Table mT = mTs[Count];

                //确定标题常量
                object sta = 0;
                object end = tTs[x].Range.Start;
                if (x != 1) sta = tTs[x - 1].Range.End;
                Range wr2 = WordDoc.Range(sta, end);

                sta = 0;
                end = mTs[Count].Range.Start - 1;
                if (Count != 1) sta = mTs[Count - 1].Range.End;

                //确定修改范围
                Range wr3 = OutWordDoc.Range(sta, end);

                index++;
                string c = Trim(wr2.Text);
                int m = 0;
                for (; m < c.Length; m++)
                {
                    int icr = (int)c[m];
                    if (icr != 47 && icr > 45 && icr < 58) continue;
                    break;
                }
                string cs = c.Substring(0, m);
                string ced = c.Substring(m, c.Length - m).Trim();
                wr3.Text = wr3.Text.Replace("{0}", ced).Replace("{i}", index.ToString()).Replace("{I}", cs);

                //Console.WriteLine(wr3.Text);
                SetStatus(index.ToString() + " -- " + ced + " 已转换!");

                //wr3.Font = font;
                //wr3.Font.Name = "微软雅黑";


                {
                    for (int i = 1; i <= mT.Rows.Count; i++)
                    {
                        #region 循环各个表
                        #region 数组情况
                        if (mT.Cell(i, 1).Range.Text.Contains("}["))
                        {
                            int AL = 0;
                            int col = 0;
                            string content = Trim(mT.Cell(i, 1).Range.Text);
                            int i1 = content.IndexOf("{");
                            int i2 = content.IndexOf("}");

                            if (i1 == -1 || i2 == -1) continue;
                            string rowstr = content.Substring(i1 + 1, i2 - i1 - 1);
                            int Row = 0;
                            if (content.IndexOf("}[") != -1)
                            {
                                Row = Dic["{" + rowstr + "}" + "[]"].point.row;
                            }
                            else
                            {
                                Row = Dic["{" + rowstr + "}"].point.row;
                            }

                            //遍历母版表,获取正确附加行号 AL
                            Table tT = tTs[x];
                            int IndexRow = 1;//记录相对行号
                            for (int ia = 1; ia <= tT.Rows.Count && IndexRow < Row; ia++)
                            {
                                int ci = 0;
                                int ARowa = 0;
                                WdColor wcc = tT.Cell(ia, 1).Range.Shading.BackgroundPatternColor;
                                for (int k = 1; k <= tT.Rows[i].Cells.Count; k++)
                                {
                                    WdColor wci = tT.Cell(ia, k).Range.Shading.BackgroundPatternColor;
                                    if (wci == wcc && wcc != WdColor.wdColorGray125) { ci++; } else break;
                                }
                                if (ci == tT.Rows[ia].Cells.Count)//该行为数组
                                {
                                    if (ARowa == ia - 1)
                                    {
                                        AL++;
                                        ARowa = ia;
                                        continue;
                                    }
                                    else
                                    {
                                        ARowa = ia;
                                    }
                                }
                                IndexRow++;

                            }


                            //根据附加行号以及行号标识,获取数组行数 
                            int ARR = 0;
                            for (int ia = Row + AL; ia <= tT.Rows.Count; ia++)
                            {
                                int ci = 0;
                                WdColor wcc = tT.Cell(ia, 1).Range.Shading.BackgroundPatternColor;
                                for (int k = 1; k <= tT.Rows[ia].Cells.Count; k++)
                                {
                                    WdColor wci = tT.Cell(ia, k).Range.Shading.BackgroundPatternColor;
                                    if (wci == wcc && wcc != WdColor.wdColorGray125) { ci++; } else break;
                                }
                                if (ci == tT.Rows[ia].Cells.Count)//该行为数组
                                {
                                    ARR++;
                                }
                                else
                                {
                                    break;
                                }
                            }


                            string colstr = "";

                            //解析数组数字

                            ColAContent[] arri = new ColAContent[mT.Rows[i].Cells.Count];

                            for (int k = 1; k <= mT.Rows[i].Cells.Count; k++)
                            {
                                string colcontent = Trim(mT.Cell(i, k).Range.Text);
                                int i3 = colcontent.IndexOf("[");
                                int i4 = colcontent.IndexOf("]");
                                col = 1;
                                //解析列值
                                if (-1 != i3 && -1 != i4)
                                {
                                    i3++;
                                    try
                                    {
                                        colstr = colcontent.Substring(i3, i4 - i3);
                                        col = int.Parse(colstr);
                                    }
                                    catch (Exception)
                                    {
                                    }
                                }
                                arri[k - 1] = new ColAContent(col, colcontent);
                            }

                            for (int ar = 1; ar <= ARR; ar++)
                            {
                                if (ar != ARR)
                                {
                                    object beforeRow = mT.Rows[i + ar - 1];
                                    mT.Rows.Add(ref beforeRow);
                                }
                                for (int ai = 0; ai < arri.Length; ai++)
                                {
                                    Cell ce = mT.Cell(i + ar - 1, ai + 1);
                                    if (ar != 1)
                                    {
                                        Cell cep = mT.Cell(i, ai + 1);
                                        ce.Range.Font = cep.Range.Font;
                                        ce.Shading.BackgroundPatternColor = cep.Shading.BackgroundPatternColor;
                                        ce.Width = cep.Width;
                                        ce.Range.ParagraphFormat.Alignment = cep.Range.ParagraphFormat.Alignment;
                                        ce.Range.Cells.Borders.OutsideLineStyle = ce.Range.Cells.Borders.OutsideLineStyle;
                                        ce.Range.Cells.Borders.InsideLineStyle = ce.Range.Cells.Borders.InsideLineStyle;
                                    }
                                    if (Dic.ContainsKey("{" + rowstr + "}[]"))
                                    {
                                        int a = Dic["{" + rowstr + "}[]"].point.row + AL;
                                        int b = arri[ai].col;
                                        string newContent = Trim(tTs[x].Cell(a, b).Range.Text);
                                        ce.Range.Text = arri[ai].content.Replace("{" + rowstr + "}[" + arri[ai].col + "]", newContent);
                                    }

                                }
                                AL++;
                            }
                        }
                        #endregion
                        else
                        {

                            for (int j = 1; j <= mT.Rows[i].Cells.Count; j++)
                            {

                                string content = Trim(mT.Cell(i, j).Range.Text);
                                int i1 = content.IndexOf("{");
                                int i2 = content.IndexOf("}");


                                if (i1 == -1 || i2 == -1) continue;
                                string rowstr = content.Substring(i1 + 1, i2 - i1 - 1);




                                #region  常数情况
                                if (rowstr.StartsWith("C"))
                                {
                                    if (Dic.ContainsKey("{" + rowstr + "}"))
                                    {
                                        string Cstr = (string)Dic["{" + rowstr + "}"].obj;
                                        mT.Cell(i, j).Range.Text = content.Replace("{" + rowstr + "}", Cstr);
                                    }
                                    continue;
                                };
                                #endregion

                                int AL = 0;



                                int Row = 0;
                                if (content.IndexOf("}[") != -1)
                                {
                                    if (Dic.ContainsKey("{" + rowstr + "}" + "[]"))
                                        Row = Dic["{" + rowstr + "}" + "[]"].point.row;
                                    else continue;
                                }
                                else
                                {
                                    if (Dic.ContainsKey("{" + rowstr + "}"))
                                        Row = Dic["{" + rowstr + "}"].point.row;
                                    else continue;
                                }

                                //遍历母版表,获取正确附加行号 AL
                                Table tT = tTs[x];
                                int IndexRow = 1;//记录相对行号
                                for (int ia = 1; ia <= tT.Rows.Count && IndexRow < Row; ia++)
                                {
                                    int ci = 0;
                                    int ARowa = 0;
                                    WdColor wcc = tT.Cell(ia, 1).Range.Shading.BackgroundPatternColor;
                                    for (int k = 1; k <= tT.Rows[i].Cells.Count; k++)
                                    {
                                        WdColor wci = tT.Cell(ia, k).Range.Shading.BackgroundPatternColor;
                                        if (wci == wcc && wcc != WdColor.wdColorGray125) { ci++; } else break;
                                    }
                                    if (ci == tT.Rows[ia].Cells.Count)//该行为数组
                                    {
                                        if (ARowa == ia - 1)
                                        {
                                            AL++;
                                            ARowa = ia;
                                            continue;
                                        }
                                        else
                                        {
                                            ARowa = ia;
                                        }
                                    }
                                    IndexRow++;

                                }
                                #region  变量情况

                                if (Dic.ContainsKey("{" + rowstr + "}"))
                                {
                                    int a = Dic["{" + rowstr + "}"].point.row + AL;
                                    int b = Dic["{" + rowstr + "}"].point.col;
                                    string Cstr = Trim(tTs[x].Cell(a, b).Range.Text);
                                    mT.Cell(i, j).Range.Text = content.Replace("{" + rowstr + "}", Cstr);
                                }


                                #endregion
                            }
                        }
                        #endregion
                        OutWordDoc.Save();
                    }

                }

            }

            WordDoc2.Close(ref oMissing, ref oMissing, ref oMissing);
            WordDoc.Close();
            SaveWord(ref OutWordDoc, fileName);
            //WordDoc.SaveAs(ref filename, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

            KillWordProcess();
            OpenWord(fileName);
        }
        static string Trim(string str)
        {
            char[] tchr = new char[] { '\r', '\a', ' ' };
            return str.Trim(tchr);
        }
        public static void KillWordProcess()
        {
            System.Diagnostics.Process[] myPs;
            myPs = System.Diagnostics.Process.GetProcesses();
            foreach (System.Diagnostics.Process p in myPs)
            {
                if (p.Id != 0)
                {
                    string myS = "WINWORD.EXE" + p.ProcessName + "  ID:" + p.Id.ToString();
                    try
                    {
                        if (p.Modules != null)
                            if (p.Modules.Count > 0)
                            {
                                System.Diagnostics.ProcessModule pm = p.Modules[0];
                                myS += "\n Modules[0].FileName:" + pm.FileName;
                                myS += "\n Modules[0].ModuleName:" + pm.ModuleName;
                                myS += "\n Modules[0].FileVersionInfo:\n" + pm.FileVersionInfo.ToString();
                                if (pm.ModuleName.ToLower() == "winword.exe")
                                    p.Kill();
                            }
                    }
                    catch
                    { }
                    finally
                    {
                        ;
                    }
                }
            }
        }
        private void button6_Click(object sender, EventArgs e)
        {
            SaveProfile(true);
        }
        private void SaveProfile(bool isForce = false)
        {
            if (isForce || checkBox3.Checked)
                sif.SaveToFile();

        }
        private bool CheckDocValid(bool isSecond = false)
        {
            if (!isSecond)
            {
                if (!choseFile1.IsValid())
                {
                    MessageBox.Show("数据源文件格式不正确!", "确认文件格式", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    SetStatus("数据源文件格式不正确!");
                    return false;
                }
            }
            if (!choseFile2.IsValid())
            {
                MessageBox.Show("模板文件格式不正确!", "确认文件格式", MessageBoxButtons.OK, MessageBoxIcon.Information);
                SetStatus("模板文件格式不正确!");
                return false;
            }
            SetStatus("文件格式通过验证!");
            SetText("转换开始,请稍后......");
            return true;
        }
        bool DToD = false;
        private void button10_Click(object sender, EventArgs e)
        {
            if (button10.Text == "取消转换")
            {
                DToD = false;
                button10.Enabled = false;
                return;
            }
            if (CheckDocValid())
            {
                MyChoseFile_TextChanged();
                if (button10.Text == "一键转换")
                {
                    button10.Text = "取消转换";
                    DToD = true;
                    Thread t = new Thread(ConvertThread);
                    t.Start();
                }
            }
        }

        public void ConvertThread()
        {

            KillWordProcess();
            try
            {
                ConvertWordFile(choseFile1.MyText, choseFile2.MyText);
            }
            catch (Exception e)
            {
                SetStatus(e.Message);
                MessageBox.Show("请检查模板是否正确!", "发生异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }


            BeginInvoke(new SetConVal(SetText), new object[] { "转换完成!" });
            SetStatus("转换完成!");
            button10.BeginInvoke(new SetConBol(SetBtn10), new object[] { true });
        }
        private void SetBtn10(bool b)
        {
            button10.Text = "一键转换";
            DToD = false;
            button10.Enabled = true;
            SetText("转换已结束!");
        }
        private void SetBtn2(bool b)
        {
            SetText("转换已停止!");
            button2.Text = "批量输出";
            button2.Enabled = true;
        }
        private void SetBtn3(bool b)
        {
            button3.Enabled = b;
            SetText("转换已结束!");
        }
        private void ConvertAllToWord()
        {
            try
            {
                // KillWordProcess();
                OutPutAllDBDoc(choseFile2.MyText);
                button2.BeginInvoke(new SetConBol(SetBtn2), new object[] { true });
            }
            catch (Exception)
            {


            }


        }
        bool banch = false;
        private void button2_Click(object sender, EventArgs e)
        {
            if (((Button)sender).Text == "取消任务")
            {
                banch = true;
                ((Button)sender).Enabled = false;
                return;
            }
            if (ValidTable())
            {
                if (CheckDocValid(true))
                {
                    MyChoseFile_TextChanged();
                    // ((Button)sender).Enabled = false;
                    ((Button)sender).Text = "取消任务";
                    Thread t = new Thread(ConvertAllToWord);
                    t.Start();
                }
            }
        }

        private void radioButton5_CheckedChanged(object sender, EventArgs e)
        {
            sif.DataSource = radioButton5.Checked;
            SaveProfile();
            SetSetingStatus();
            LoadData(sif.DataSource);
        }

        private void LoadData(bool dataType = true, bool isForce = false)
        {
            if (dataType)
            {
                DisplayDataString = userControl11.MyText;
            }
            else
            {
                DisplayDataString = choseFile1.MyText;
            }

            if (dic.ContainsKey(DisplayDataString))
            {
                List<string> lis = new List<string>();

                foreach (KeyValuePair<string, TableInfo> item in dic[DisplayDataString])
                {
                    lis.Add(item.Key);
                }
                string str = comboBox1.Text;
                string[] tabs = lis.ToArray();
                AddDataToComBoBox(tabs);
            }
            else comboBox1.Items.Clear();
            ValidTable();
            if (dataType)
            {

                if (!dic.ContainsKey(userControl11.MyText))
                    TestConnect();
                else RefreashData();
            }
            else
            {

                if (!choseFile1.IsValid())
                {
                    MessageBox.Show("数据源文件格式不正确!", "确认文件格式", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    SetStatus("数据源文件格式不正确!");
                    return;
                }
                else
                {
                    if (!dic.ContainsKey(choseFile1.MyText) || isForce)
                    {


                        KillWordProcess();
                        Thread t = new Thread(GetWordDataSource);
                        t.Start();

                    }
                    else
                    {
                        if (!dic[choseFile1.MyText].ContainsKey(comboBox1.Text))
                        {
                            SetInfo();
                        }
                        else
                        {
                            RefreashData();
                        }
                    }
                }

            }

        }
        bool RaidoIsAccess = true;
        private void GetWordDataSource()
        {
            DisplayDataString = choseFile1.MyText;
            if (!RaidoIsAccess)
            {
                return;
            }
            RaidoIsAccess = false;
            SetStatus("文件加载已开始!");
            List<string> datasource = new List<string>();
            Object oMissing = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
            Microsoft.Office.Interop.Word.Document WordDoc = WordApp.Documents.Open(choseFile1.MyText);
            Tables tTs = WordDoc.Tables;

            #region 循环各表
            SetStatus("开始处理文件中的表!");
            try
            {
                int tTsCount = tTs.Count;
                for (int l = 0; l < tTsCount; l++)
                {
                    if (isStopConvert)
                    {
                        isStopConvert = false;
                        break;
                    }
                    try
                    {

                        Table tT = tTs[l + 1];

                        object sta = 0;
                        object end = tTs[l + 1].Range.Start - 1;
                        if (l != 0) sta = tTs[l].Range.End;
                        Range wr2 = WordDoc.Range(sta, end);
                        string c = Trim(wr2.Text);
                        int m = 0;
                        for (; m < c.Length; m++)
                        {
                            int icr = (int)c[m];
                            if (icr != 47 && icr > 45 && icr < 58) continue;
                            break;
                        }
                        string ced = c.Substring(m, c.Length - m).Trim();
                        #region 生成模板
                        Dictionary<string, CellElement> Dic = new Dictionary<string, CellElement>();
                        CellElement ce0 = new CellElement();
                        ce0.obj = ced;
                        ce0.type = TypeOfElement.STRING;
                        ce0.point = new Point(0, 0);
                        Dic["{0}"] = ce0;
                        DataTable dt = new DataTable();
                        int C = 1, A = 1;
                        int ARow = 0;
                        int tTRowsCount = tT.Rows.Count;
                        for (int i = 1; i <= tTRowsCount; i++)
                        {

                            int cj = 0;
                            int tTRowsiCellsCount = tT.Rows[i].Cells.Count;
                            for (int k = 1; k <= tTRowsiCellsCount; k++)
                            {
                                WdColor wci = tT.Cell(i, k).Range.Shading.BackgroundPatternColor;
                                if (wci == WdColor.wdColorGray125) { cj++; };
                            }

                            if (cj == tTRowsiCellsCount)
                            {
                                for (int j = 2; j <= tTRowsiCellsCount; j++)
                                {
                                    dt.Columns.Add(Trim(tT.Cell(i, j).Range.Text));
                                }
                                continue;
                            }

                            int ci = 0;
                            WdColor wcc = tT.Cell(i, 1).Range.Shading.BackgroundPatternColor;

                            for (int k = 1; k <= tTRowsiCellsCount; k++)
                            {
                                WdColor wci = tT.Cell(i, k).Range.Shading.BackgroundPatternColor;
                                if (wci == wcc && wcc != WdColor.wdColorGray125) { ci++; } else break;

                            }

                            if (ci == tTRowsiCellsCount)
                            {
                                //AddArowTo DataTable
                                List<object> lobs = new List<object>();
                                for (int j = 2; j <= tTRowsiCellsCount; j++)
                                {
                                    if (j == tTRowsiCellsCount)
                                    {
                                        string col_desc = Trim(tT.Cell(i, 1).Range.Text) + ";" + Trim(tT.Cell(i, j).Range.Text);
                                        lobs.Add(col_desc);
                                        if (SaveAllDescInstance)
                                            SaveColDescriptionByInfo(Dic["{1}"].obj.ToString(), Trim(tT.Cell(i, 2).Range.Text), col_desc);
                                        break;
                                    }
                                    lobs.Add(Trim(tT.Cell(i, j).Range.Text));
                                }
                                dt.Rows.Add(lobs.ToArray());
                                if (ARow == i - 1)
                                {
                                    ARow = i;
                                    continue;
                                }
                                else
                                {
                                    ARow = i;
                                }
                            }
                            for (int j = 1; j <= tTRowsiCellsCount; j++)
                            {

                                if (ci == tTRowsiCellsCount)
                                {
                                    CellElement ce = new CellElement();
                                    ce.point = new Point(i, 0);
                                    ce.type = TypeOfElement.ARRAY;
                                    Dic.Add("{" + A + "}[]", ce);
                                    A++;
                                    break;
                                }
                                else
                                {
                                    WdColor wc = tT.Cell(i, j).Range.Shading.BackgroundPatternColor;
                                    CellElement ce = new CellElement();
                                    ce.point = new Point(i, j);
                                    ce.obj = Trim(tT.Cell(i, j).Range.Text);
                                    if (wc == WdColor.wdColorGray125)
                                    {
                                        ce.type = TypeOfElement.CONST;
                                        Dic.Add("C" + C, ce);
                                        C++;
                                    }
                                    else
                                    {
                                        ce.type = TypeOfElement.STRING;
                                        Dic.Add("{" + A + "}", ce);
                                        A++;
                                    }

                                }
                            }
                        }
                        TableInfo ti = new TableInfo(Dic["{1}"].obj.ToString(), l);
                        ti.Description = Dic["{0}"].obj.ToString();
                        if (Dic.ContainsKey("{2}") && Dic["{2}"].obj.ToString() != "")
                        {
                            ti.Description += ";";
                            ti.Description += Dic["{2}"].obj.ToString();
                        }
                        ti.dt = dt;
                        if (!dic.ContainsKey(choseFile1.MyText))
                        {
                            dic[choseFile1.MyText] = new Dictionary<string, TableInfo>();
                        }
                        dic[choseFile1.MyText][ti.TabName] = ti;
                        datasource.Add(ti.TabName);
                        SetStatus((l + 1).ToString() + " -- " + ti.TabName + " 已提取!");
                        if (!isRefreashing || !sif.DataSource)
                            comboBox1.Invoke(new AddDataSource(AddDataSourceComb), new object[] { ti.TabName });
                        if (SaveAllDescInstance)
                            SaveTabDescription(ti.TabName, ti.Description);
                        #endregion

                    }
                    catch (Exception e)
                    {
                        SetStatus("异常:" + e.Message);
                        continue;
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "处理异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            if (isRefreashing) isRefreashing = false;
            SetStatus("文件处理结束!");
            RaidoIsAccess = true;
            if (SaveAllDescInstance) SaveAllDescInstance = false;
            #endregion

        }
        private void AddDataSourceComb(string ds)
        {
            if (sif.DataSource) return;
            List<string> ls = new List<string>();
            if (comboBox1.Items.Count != 0)
            {

                foreach (var item in comboBox1.Items)
                {
                    ls.Add(item.ToString());
                }

            }

            if (!ls.Contains(ds))
            {
                ls.Add(ds);
                string str = comboBox1.Text;
                comboBox1.Items.Add(ds);
                if (str != "")
                {
                    comboBox1.Text = str;
                }
            }
            if (comboBox1.Text == ds)
                RefreashData();
        }
        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton cb = (RadioButton)sender;
            if (cb.Checked)
            {
                switch (cb.Text)
                {
                    case "MySql":
                        if (sif.DataBaseType != 0)
                        {
                            sif.DataBaseType = 0;
                            SaveProfile();
                        }
                        break;
                    case "Oracle":
                        if (sif.DataBaseType != 1)
                        {
                            sif.DataBaseType = 1;
                            SaveProfile();
                        }
                        break;
                    case "SqlServer":
                        if (sif.DataBaseType != 2)
                        {
                            sif.DataBaseType = 2;
                            SaveProfile();
                        }
                        break;
                    default:
                        break;
                }
            }
        }

        private void MyChoseFile_TextChanged()
        {
            if (choseFile1.MyText != sif.input)
            {
                sif.input = choseFile1.MyText;
            }
            if (choseFile2.MyText != sif.output)
            {
                sif.output = choseFile2.MyText;
            }

        }

        private void checkBox3_CheckedChanged(object sender, EventArgs e)
        {
            sif.isAutoSetting = checkBox3.Checked;
            SaveProfile(true);
            SetSetingStatus();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            SaveColsToDb(textBox5.Text, textBox6.Text);
        }

        private void textBox5_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SaveColsToDb(textBox5.Text, textBox6.Text);
            }
        }

        private void button12_Click(object sender, EventArgs e)
        {
            DoModel();
            string str = f2.richTextBox1.Text;
            if (dic.ContainsKey(DisplayDataString))
            {
                string path = TempTxtPath;
                string codes = "";
                int i = 0;
                foreach (KeyValuePair<string, TableInfo> item in dic[DisplayDataString])
                {
                    i++;
                    if (checkBox2.Checked)
                    {
                        DataTable dt = GetColumnsDesc(item.Key);
                        bool flag = false;
                        if (dt != null)
                        {
                            foreach (DataRow dr in dt.Rows)
                            {
                                if (dr.ItemArray[0].ToString().Contains(textBox4.Text))
                                {
                                    flag = true;
                                    break;
                                }
                            }
                        }
                        if (!flag) continue;
                    }
                    string codes_t = str.Replace("{0}", item.Key).Replace("{i}", i.ToString());
                    codes_t = RpRecord(codes_t, item.Key);
                    codes += codes_t;
                    codes += "\r\n";
                }
                if (codes != "")
                {
                    MyClass.WriteFile(path, codes);
                    SetStatus("代码生成成功!");
                    Process.Start("notepad", path);
                }
                else SetStatus("代码生成为空!");

            }
            else
            {
                SetStatus("数据未加载,代码生成失败!");
            }

        }
        private string RpRecord(string codes, string table, string column = "")
        {
            int s = codes.IndexOf("<re-li>");
            int e = codes.IndexOf("</re-li>");
            string rbuf = "";
            if (s != -1 && e != -1 && e > s)
            {
                string buff = codes.Substring(s, e - s + 8);
                string buff_in = buff.Substring(7, e - s - 7).TrimStart(new char[] { '\r', '\n' });
                DataTable dt = GetColumnsDesc(table);
                if (dt != null)
                {
                    int j = 0;
                    foreach (DataRow dr in dt.Rows)
                    {
                        j++;
                        if (column == "" || dr[0].ToString() == column)
                            rbuf += buff_in.Replace("{1}", dr.ItemArray[0].ToString()).Replace("{j}", j.ToString()).Replace("{2}", dr.ItemArray[4].ToString().Split(';')[0]);
                    }
                }
                return codes.Replace(buff, rbuf.TrimEnd(new char[] { '\r', '\n' }));
            }
            return codes;
        }
        private void button11_Click(object sender, EventArgs e)
        {
            if (ValidTable())
            {
                DoModel();
                bool flag = false;
                if (checkBox2.Checked)
                {
                    DataTable dt = GetColumnsDesc(comboBox1.Text);
                    if (dt != null)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            if (dr.ItemArray[0].ToString().Contains(textBox4.Text))
                            {
                                flag = true;
                                break;
                            }
                        }
                    }
                }
                if (!checkBox2.Checked || flag)
                {
                    string path = TempTxtPath;
                    string str = f2.richTextBox1.Text.Trim();
                    string codes = str.Replace("{0}", comboBox1.Text);
                    codes = RpRecord(codes, comboBox1.Text);
                    MyClass.WriteFile(path, codes);
                    SetStatus("单表代码生成成功!");
                    Process.Start("notepad", path);
                }
                else
                {
                    SetStatus("不满足过滤条件,单表代码生成失败!");
                }
            }
        }
        private void DoModel()
        {
            if (f2.checkBox1.Checked || f2.richTextBox1.Text.Trim() == "")
                f2.ShowDialog();
        }

        private void DoModelDC(bool dc = false)
        {
            if (dc)
            {
                if (!f2.checkBox3.Checked || f2.textBox1.Text.Trim() == "")
                    f2.ShowDialog();
            }
        }
        Form2 f2 = new Form2();

        private void button13_Click(object sender, EventArgs e)
        {

            if (ValidTable())
            {

                DataTable dt = GetColumnsDesc(comboBox1.Text);
                string str = "public class " + comboBox1.Text + "\r\n{\r\n";
                if (dt != null)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        str += "\tpublic string ";
                        str += dr.ItemArray[0].ToString();
                        str += " = \"\";\r\n";
                    }
                }
                str += "}";
                string path = TempTxtPath;
                MyClass.WriteFile(path, str);
                SetStatus("单表代码生成成功!");
                Process.Start("notepad", path);

            }
        }
        public const Int32 WM_SYSCOMMAND = 0x112;
        public const Int32 MF_SEPARATOR = 0x800;
        public const Int32 MF_BYPOSITION = 0x400;
        public const Int32 MF_STRING = 0x0;
        public const Int32 IDM_HELP = 1000;

        [DllImport("user32.dll")]
        private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
        [DllImport("user32.dll")]
        private static extern bool InsertMenu(IntPtr hMenu, Int32 wPosition, Int32 wFlags, Int32 wIDNewItem, string lpNewItem);
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_SYSCOMMAND)
            {
                switch (m.WParam.ToInt32())
                {
                    case IDM_HELP:
                        ShowHelp();
                        return;
                    default:
                        break;
                }
            }
            try
            {
                base.WndProc(ref m);
            }
            catch (Exception)
            {

                ;
            }

        }
        private void button14_Click(object sender, EventArgs e)
        {

            if (dic.ContainsKey(DisplayDataString))
            {
                string str = "";
                bool flag = true;
                foreach (KeyValuePair<string, TableInfo> item in dic[DisplayDataString])
                {
                    DataTable dt = GetColumnsDesc(item.Key);
                    if (checkBox2.Checked)
                    {
                        flag = item.Key.Contains(textBox4.Text);
                        if (!flag) continue;
                    }
                    if (str != "") str += "\r\n\r\n";
                    str += "public class " + item.Key + "\r\n{\r\n";
                    if (dt != null)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            str += "\tpublic string ";
                            str += dr.ItemArray[0].ToString();
                            str += " = \"\";\r\n";
                        }
                    }
                    str += "}";
                }
                if (str != "")
                {
                    string path = TempTxtPath;
                    MyClass.WriteFile(path, str);
                    SetStatus("实体生成成功!");
                    Process.Start("notepad", path);
                }
                else SetStatus("实体生成为空!");

            }
            else
            {
                SetStatus("数据未加载,实体生成失败!");
            }

        }

        private void comboBox1_TextUpdate(object sender, EventArgs e)
        {

            ComboBox comAutoSelect = (ComboBox)sender;
            int start = comAutoSelect.SelectionStart;
            string text = comAutoSelect.Text;
            string input = comAutoSelect.Text.ToLower();
            string[] data = GetComBoBoxData();
            comAutoSelect.Items.Clear();

            if (string.IsNullOrEmpty(input)) comAutoSelect.Items.AddRange(data);
            else
            {
                string[] newList = SelectArray(data, input);
                comAutoSelect.Items.AddRange(newList);
            }
            if (!comAutoSelect.DroppedDown)
                comAutoSelect.DroppedDown = comAutoSelect.Items.Count != 0;
            comAutoSelect.Text = text;
            comAutoSelect.Select(start, 0);
            ////保持鼠标指针形状  
            Cursor = Cursors.Default;
            RedrawWindow(GetDesktopWindow(), null, IntPtr.Zero, 0x85);
        }

        private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
        {

            System.Drawing.Font myFont = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); ;
            ComboBox comAutoSelect = (ComboBox)sender;

            e.DrawBackground();
            System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(2, e.Bounds.Top + 2,
e.Bounds.Height, e.Bounds.Height - 4);
            System.Drawing.Brush b = System.Drawing.Brushes.Gray;
            if (comAutoSelect.Items[e.Index].ToString().ToLower().Contains(comAutoSelect.Text.ToLower()))
            {
                myFont = new System.Drawing.Font("宋体", 12F, System.Drawing.FontStyle.Italic | System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(134))); ;
                b = System.Drawing.Brushes.MidnightBlue;

            }


            e.Graphics.DrawString(comAutoSelect.Items[e.Index].ToString(), myFont, b, new RectangleF(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height));
            e.DrawFocusRectangle();
        }

        private void button16_Click(object sender, EventArgs e)
        {
            if (ValidTable())
            {
                string result = FormatSqlString(comboBox1.Text)[Int32.Parse((sender as Button).Tag.ToString())];
                if (checkBox4.Checked)
                {
                    Clipboard.SetDataObject(result);
                    SetStatus("语句已经设置到剪贴板!");
                }
                else
                {
                    string path = TempTxtPath;
                    MyClass.WriteFile(path, result);
                    SetStatus("Sql语句已经输出!");
                    Process.Start("notepad", path);
                }
            }
        }
        public string[] FormatSqlString(string table, string selectstr = "", string existcols = "")
        {
            string[] Sqls = new string[4];
            string[] records = GetTableRecords(table);

            string sels = "";
            if (selectstr == "*") sels = "*";
            else if (selectstr == "")
            {
                sels = "";
                foreach (string item in records)
                {
                    if (sels != "")
                    {
                        sels += ",";
                    }
                    sels += item;
                }

            }
            else
            {
                string[] selcols = selectstr.Split(',');
                foreach (string item in selcols)
                {
                    if (sels != "") sels += ",";
                    sels += string.Format(item.Trim('\''), records);
                }
            }

            string where = "";
            if (existcols != "")
            {
                string[] exicols = existcols.Split(',');

                foreach (string item in exicols)
                {
                    if (where != "") where += " AND ";
                    where += string.Format(item.Trim('\''), records);
                    where += "=";
                    where += item;
                }
            }
            string sql = "SELECT " + sels + " FROM " + table;
            if (where != "") sql += " WHERE " + where;
            Sqls[0] = sql;

            sql = "";
            {

                string val = "";
                foreach (string item in records)
                {
                    if (sql != "")
                    {
                        sql += ",";
                        val += ",";
                    }
                    sql += item;
                    val += "'" + item + "'";
                }

                sql = "INSERT INTO " + table + "(" + sql + ")";
                sql += "\r\nVALUES (" + val + ")";
            }
            Sqls[1] = sql;


            where = "";

            {

                foreach (string item in records)
                {
                    if (where != "") where += " AND ";
                    where += item;
                    where += "=";
                    where += "'" + item + "'";
                }
            }

            sql = "";

            {

                foreach (string item in records)
                {
                    if (sql != "")
                    {
                        sql += ",";
                    }
                    sql += item;
                    sql += "=";
                    sql += "'" + item + "'";
                }
                sql = "UPDATE " + table + " SET " + sql;
                if (where != "") sql += "\r\nWHERE  " + where;
            }
            Sqls[2] = sql;



            sql = "DELETE FROM " + table;
            if (where != "") sql += "\r\nWHERE  " + where;
            Sqls[3] = sql;

            return Sqls;
        }

        private string[] GetTableRecords(string table)
        {
            DataTable dt = GetColumnsDesc(table);
            List<string> ls = new List<string>();
            if (dt != null)
            {

                foreach (DataRow dr in dt.Rows)
                {

                    ls.Add(dr.ItemArray[0].ToString());
                }
            }
            return ls.ToArray();
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (!f2.checkBox2.Checked) return;
            try
            {
                string result = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
                if (e.ColumnIndex == 1 && ValidTable())
                {

                    Clipboard.SetDataObject(result);
                    SetStatus("字段名称" + result + ",已设置到剪贴板!");
                }
                else if (e.ColumnIndex == 2) ProcessDC(result);
            }
            catch (Exception)
            {
                SetStatus("字段设置到剪贴板发生异常!");
            }
        }
        private void ProcessDC(string result, bool pop = false)
        {
            DoModelDC(pop);
            if (f2.checkBox3.Checked)
            {

                string str = f2.textBox1.Text.Trim();
                str = str.Replace("<re-li>", "");
                str = str.Replace("</re-li>", "");
                str = "<re-li>" + str + "</re-li>";

                string codes = str.Replace("{0}", comboBox1.Text);
                codes = RpRecord(codes, comboBox1.Text, result);
                Clipboard.SetDataObject(codes);
                SetStatus(codes + ",已设置到剪贴板!");

            }
            else
            {
                SetStatus("开关标志未打开，未设置到剪贴板!");
            }
        }
        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                string result = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
                if (e.ColumnIndex == 1 && ValidTable())
                {

                    Clipboard.SetDataObject(result);
                    SetStatus("字段名称" + result + ",已设置到剪贴板!");
                }
                else if (e.ColumnIndex == 2) ProcessDC(result,true);
            }
            catch (Exception)
            {
                SetStatus("字段设置到剪贴板发生异常!");
            }
        }

    }

    public delegate void AddDataSource(string b);
    public delegate void SetConBol(bool b);
    public delegate void SetConVal(string str);
    public class SettingInfo
    {
        private string path = Path.Combine(MyClass.TempDir, "setting.ini");

        public SettingInfo()
        {
            if (!File.Exists(path))
            {
                return;
            }
            FileInfo fi = new FileInfo(path);
            StreamReader sr = fi.OpenText();
            string temp = "";
            Dictionary<string, string> nv = new Dictionary<string, string>();
            while (!sr.EndOfStream)
            {
                temp = sr.ReadLine();
                if (temp.Contains(" "))
                {
                    string pattern = "\\s+";
                    string replacement = " ";
                    System.Text.RegularExpressions.Regex rgx = new System.Text.RegularExpressions.Regex(pattern);
                    temp = rgx.Replace(temp, replacement).Trim();
                    if (temp == "" || !temp.Contains(" ")) continue;
                    nv[temp.Substring(0, temp.IndexOf(' '))] = temp.Substring(temp.IndexOf(' '));
                }

            }
            sr.Close();
            if (nv.ContainsKey("input"))
            {
                try
                {
                    input = nv["input"].Trim();
                }
                catch (Exception)
                {
                }
            }
            if (nv.ContainsKey("output"))
            {
                try
                {
                    output = nv["output"].Trim();
                }
                catch (Exception)
                {
                }
            }
            if (nv.ContainsKey("TabSelIndex"))
            {
                try
                {
                    TabSelIndex = int.Parse(nv["TabSelIndex"]);
                }
                catch (Exception)
                {
                }
            }
            if (nv.ContainsKey("DataBaseType"))
            {
                try
                {
                    DataBaseType = int.Parse(nv["DataBaseType"]);
                }
                catch (Exception)
                {
                }
            }
            if (nv.ContainsKey("isAutoSave"))
            {
                try
                {
                    isAutoSave = bool.Parse(nv["isAutoSave"]);
                }
                catch (Exception)
                {
                }
            }
            if (nv.ContainsKey("isAutoSetting"))
            {
                try
                {
                    isAutoSetting = bool.Parse(nv["isAutoSetting"]);
                }
                catch (Exception)
                {
                }
            }
            if (nv.ContainsKey("DataSource"))
            {
                try
                {
                    isAutoSave = bool.Parse(nv["DataSource"]);
                }
                catch (Exception)
                {
                }
            }

        }
        public bool isAutoSave = false;
        public bool isAutoSetting = true;
        public bool DataSource = true;
        public int TabSelIndex = 0;
        public int DataBaseType = 0;
        public string input = "";
        public string output = "";
        public void SaveToFile()
        {
            string ws = "isAutoSave" + " " + isAutoSave.ToString();
            ws += "\r\nDataSource" + " " + DataSource.ToString();
            ws += "\r\nTabSelIndex" + " " + TabSelIndex.ToString();
            ws += "\r\nDataBaseType" + " " + DataBaseType.ToString();
            ws += "\r\nisAutoSetting" + " " + isAutoSetting.ToString();
            ws += "\r\ninput" + " " + input;
            ws += "\r\noutput" + " " + output;
            MyClass.WriteFile(path, ws, true, false);
        }
    }
    public class MyClass
    {
        public static string GetNowTime()
        {
            return string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now);
        }
        public static string TempDir
        {
            get
            {
                return Path.GetFullPath(System.Environment.GetEnvironmentVariable("TEMP"));
            }
        }
        public static string TempFile
        {
            get
            {
                return Path.GetFullPath(Path.Combine(TempDir, GetNowTime().Replace(':', '-')));
            }
        }
        public static void CreateFile(string path)
        {
            if (!File.Exists(path))
            {
                FileInfo f = new FileInfo(path);
                FileStream wn = f.OpenWrite();
                wn.Close();
            }
        }
        public static void CreateFile(string path, string content, bool isRecreate, bool isGBK = true)
        {
            if (File.Exists(path))
            {
                if (!isRecreate)
                {
                    FileInfo f = new FileInfo(path);
                    try
                    {
                        StreamWriter wn = f.AppendText();
                        wn.WriteLine(content);
                        wn.Close();

                    }
                    catch (Exception)
                    {
                    }
                    return;
                }
                else
                {
                    try
                    {
                        File.Delete(path);
                    }
                    catch (Exception)
                    {

                        return;
                    }
                }
            }
            string dir = Path.GetDirectoryName(path);
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);
            FileInfo f1 = new FileInfo(path);
            FileStream wn1 = f1.Create();
            byte[] b = isGBK ? System.Text.Encoding.Default.GetBytes(content) : System.Text.Encoding.UTF8.GetBytes(content);
            wn1.Write(b, 0, b.Length);
            wn1.Close();
        }

        public static void WriteFile(string path, string content, bool isReCreate = false, bool isGBK = true)//string path,
        {
            CreateFile(path, content, isReCreate, isGBK);
        }
    }
    public class TableInfo
    {
        public TableInfo(string Name, int i = 0, string Desc = "")
        {
            TabName = Name;
            Description = Desc;
            index = i;
        }
        public string TabName = "";
        public string Description = "";
        public DataTable dt = null;
        public int index = 0;
    }
    public struct Point
    {
        public Point(int i, int j)
        {
            row = i; col = j;
        }
        public int row;
        public int col;
    }
    public enum TypeOfElement
    {
        CONST,
        STRING,
        ARRAY
    }
    public class CellElement
    {
        public TypeOfElement type = TypeOfElement.STRING;
        public object obj;
        public Point point;
    }
    public struct ColAContent
    {
        public ColAContent(int c, string con)
        {
            col = c;
            content = con;
        }
        public int col;
        public string content;

    }
}
